<?php
/**
*
*/
class mobileapi_rpc_member extends mobileapi_frontpage{
	private $data_post; //post 过滤后的数组
	private $page_nums; //每页显示的条数
    private $offset;	//偏移量
    private $n_page;	//第几页
	private $where = 'WHERE 1';

	function __construct($app)
	{
		parent::__construct($app);
		$this->app = $app;
		$this->verify_member();
        $this->member = $this->get_current_member();
		$this->app->rpcService = kernel::single('base_rpc_service');
        $this->pagesize = 10;


		$this->data_post = $this->check_input($_POST);
		//初始化分页处理
		if($this->data_post['page_no'] > 0){
			$this->data_post['n_page'] = $this->data_post['page_no'];
		}
		$this->page_nums = $this->data_post['page_nums']?$this->data_post['page_nums'] : 10;//默认10条
		$this->n_page = $this->data_post['n_page'] ? $this->data_post['n_page'] : 1;
		$this->offset = ($this->n_page - 1) * $this->page_nums;
		if($this->data_post['order'] == 'null'){
			$this->data_post['orderby'] = '';
		}

	}
        //积分规则
        public function exp($key,$member_id,$type=true){
            $exps = array(
                'upload_avatar' => 5,
                'opinions_praise' => 1,
                'get_praise' => 2,
                'opinions_comment' => 2,
                'opinions' => 20,
                'opinions_fancy' => 80,

            );
            $exp = $type ? $exps[$key] : 0-(int)$exps[$key];
            $member = app::get("b2c")->model("members")->getRow("*",array('member_id'=>$member_id));
            return app::get("b2c")->model("members")->update(array('experience'=>$member['experience']+$exp),array('member_id'=>$member_id));

        }
	//查看用户是否填写身份证号码
	public function checkCard(){
		  $member_id = empty($_POST['member_id'])?$_SESSION['account']['member']:$_POST['member_id'];
		  //获取该用户订单
		  $m_order = app::get('b2c')->model('orders');
		  $where = array(
			'member_id' => $member_id,
			'status' => 'active',
            'pay_status' => 1,
		  );
		  $order = $m_order->count($where);
		  //获取用户信息
		  $m_member = app::get('b2c')->model('members');
		  $where = array(
			'member_id' => $member_id,
		  );
		  $member = $m_member->getList('identity' ,$where);
		  if($order > 0 AND ( $member[0]['identity'] == '' OR $member[0]['identity'] == null ) ){
			  return 'erro';
		  }else{
			  return 'succ';
		  }
	}


	/**
     * 取到个人信息字段
     * @param null
     * @return string json
    */
	public function setting()
	{
		$userObject = kernel::single('b2c_user_object');
		$membersData = $userObject->get_pam_data('*',$this->app->member_id);
		//foreach ($membersData as $value) {

 		//}

		$attr = kernel::single('b2c_user_passport')->get_signup_attr($this->app->member_id);
		foreach ($attr as $key => $value) {
			unset($attr[$key]['attr_order'], $attr[$key]['attr_search'], $attr[$key]['attr_group'], $attr[$key]['attr_sdfpath']);
			if ($value['attr_column'] == 'profile[gender]') {
				$attr[$key]['attr_option'][] = 'male';
				$attr[$key]['attr_option'][] = 'female';
			}
			if ($value['attr_type'] == 'checkbox')
				$attr[$key]['attr_column'] = 'box:'.$value['attr_column'];
		}

		return array('mem' => 'null', 'attr' => $attr);

		/*
			attr 字段列表
			attr_id =>   ID
            attr_show => 是否显示
            attr_name => 显示名称
            attr_type => 字段类型			checkbox(多选类型)||gender(单选类型)||text(文本类型)||select(单选类型)||....
            attr_required => 是否必填 	bool(true为必填)
            attr_option => 字段选项类型数据数组
            			[0] => value
						[1] => value
            attr_valtype =>
            attr_tyname => 字段项类型
            attr_column => 字段name
            attr_sdfpath =>
            attr_value => 保存后字段值			值||array()
		*/
	}
    function check_identity(){

        $code=app::get('b2c')->model('members')->getList('identity',array('member_id'=>$this->app->member_id));

        if($code[0]['identity']!=''){
           return true;
        }
        return false;
    }


    function set_token(){

        $token =  $_POST['token'];
      if ($token=='') {
          $token =  $_POST['itoken'];
      }
        if ($token=='') {
          $token =  $_POST['atoken'];
      }
        if ($token) {
            $_data  = array (
                            'token'   => $token,
                            );
            $mdl    = app::get('b2c')->model('members');
            $mdl->update( $_data, array( 'member_id' => $this->app->member_id));
        }
    }

      // 得到普通会员
    public function get_ptmember(){

        $member_id = $this->app->member_id;
         $count = kernel::database()->select("SELECT count(*) as total FROM sdb_b2c_members where invite_mem_fid = {$this->app->member_id} and member_lv_id = '1' and member_type = '1'");
        if($res= kernel::single('b2c_mdl_members')->getList('name,member_id',array('invite_mem_fid'=>$this->app->member_id,'member_lv_id'=>'1','member_type'=>'1'),$this->offset,$this->page_nums,$this->data_post['orderby'])){
               foreach ($res as $k => $v) {
               $res[$k]['mobile'] = $this->get_mobile($v['member_id']);
            }
            $this->app->rpcService->send_user_success('200',$res,$count[0]['total']);
         }
         return '';
    }

          // 得到潜在会员
    public function get_qzmember(){

        $member_id = $this->app->member_id;
         $count = kernel::database()->select("SELECT count(*) as total FROM sdb_b2c_members where invite_mem_fid = {$this->app->member_id} and member_lv_id = '4' and member_type = '1'");
        if($res= kernel::single('b2c_mdl_members')->getList('name,member_id',array('invite_mem_fid'=>$this->app->member_id,'member_lv_id'=>'4','member_type'=>'1'),$this->offset,$this->page_nums,$this->data_post['orderby'])){
               foreach ($res as $k => $v) {
               $res[$k]['mobile'] = $this->get_mobile($v['member_id']);
            }
            $this->app->rpcService->send_user_success('200',$res,$count[0]['total']);
         }
         return '';
    }


	/**
     * 保存个人信息
     * @param  mixed
     * @return string json
     * @提交例子 '&contact[name]=测试&contact[area]=&profile[gender]=female&box:testing[]=选项1&box:testing[]=选项2&sfa=2222'
    */
	public function save_setting()
	{
        $member_model = app::get('b2c')->model('members');
        $userPassport = kernel::single('b2c_user_passport');
        $desc=$_POST['desc'];
        $_POST = $this->check_input($_POST);
        if($_POST['local_name'] && !$userPassport->set_local_uname(strtolower($_POST['local_name']),$msg)){
            $this->app->rpcService->send_user_error('4003', $msg);
        }

        foreach($_POST as $key=>$val){
            if(strpos($key,"box:") !== false){
                $aTmp = explode("box:",$key);
                $_POST[$aTmp[1]] = serialize($val);
            }
        }


        //--防止恶意修改
        $attr = app::get('b2c')->model('member_attr')->getList('attr_column');
        foreach($attr as $attr_colunm){
            $colunm = $attr_colunm['attr_column'];
            $arr_colunm[] = $colunm;
        }
        foreach($_POST as $post_key=>$post_value){
            if( !in_array($post_key,$arr_colunm) || !$post_value){
                unset($_POST[$post_key]);
            }
        }
        //---end

        $filter['member_id'] = $this->app->member_id;
        //return $_POST;
        if($desc){
            $_POST['qianming'] = $desc;
        }
        if($member_model->update($_POST,$filter)){
            //增加会员同步 2012-05-15
            if( $member_rpc_object = kernel::service("b2c_member_rpc_sync") ) {
                $member_rpc_object->modifyActive($_POST['member_id']);
            }
            return true;
        }else{
            $this->app->rpcService->send_user_error('4003', '更新失败');
        }
	}

    function save_desc(){
        $member_model = app::get('b2c')->model('members');
        $data=array(
            'qianming'=>$_POST['desc'],
            );
        if ($member_model->update( $data, array( 'member_id' => $this->app->member_id))) {
             return 'succ';
        }

    }

	/**
     * 保存修改密码
     * @param array
     * @return string json
    */
	public function save_security()
	{
		$userPassport = kernel::single('b2c_user_passport');
		$result = $userPassport->save_security($this->app->member_id,$_POST,$msg);
		if($result){
            return true;
        }else{
            $this->app->rpcService->send_user_error('4003', $msg);
        }
	}

	//我的订单
    public function orders($param=array())
    {
		//return $_POST;
        $nPage = $param['n_page'] ? $param['n_page'] : 1;
		if(isset($param['pay_status'])){
			$pay_status = $param['pay_status'];  // 支付状态
		}
		if(isset($param['ship_status'])){
			$ship_status = $param['ship_status']; //发货状态
		}
		if(isset($param['status'])){
			$status = $param['status'];  //订单状态
		}
		if(isset($param['createtime_status'])){
			$createtime_status = $param['createtime_status']; //订单时间
		}

        $order = app::get('b2c')->model('orders');
        if($param['bn'] || $param['name'] || $param['order_id']){
            if($param['bn'] || $param['name']){
                if(isset($param['bn'])){
                    $filter['bn'] = $param['bn'];
                }else{
                    $filter['name'] = $param['name'];
                }
                $order_ids = app::get('b2c')->model('order_items')->getlist('order_id',$filter,($nPage-1)*11,11);
                foreach($order_ids as $v){
                    $order_id[]= $v['order_id'];
                }
            }elseif($param['order_id']){
                $order_id = $param['order_id'];
            }else{
                return false;
            }
            $filter['order_id'] = $order_id;
            $filter['member_id'] = $this->app->member_id;
            $aData = $order->fetchByMemberSearch($filter,$nPage);
        }elseif (!isset($param['pay_status']) && !isset($param['ship_status']) && !isset($param['status']) && !isset($param['createtime_status'])){
            $aData = $order->fetchByMember($this->app->member_id,$nPage);
        } else {
            $order_status = array();
                        //return $pay_status;
            //支付状态
            if (isset($pay_status) && $pay_status <= 5) {
                $order_status['pay_status'] = $pay_status;
                $order_status['status'] = 'active';
            }

            // 发货状态
            if (isset($ship_status) && $ship_status <= 4) {
                 $order_status['pay_status'] = 1;
                $order_status['ship_status'] = $ship_status;
                $order_status['status'] = 'active';
            }

            //订单状态
            if (isset($status) && $status == 'finish') {
                $order_status['status'] = 'finish';
            }


            //一个月前的订单
            if ($createtime_status == 'prior_to'){
                $ago = time() - 86400 * 31;
                $order_status['createtime_to'] = $ago;
            } elseif ($createtime_status == 'recent') {
                $ago = time() - 86400 * 31;
                $order_status['createtime_from'] = $ago;
            }
			//return $order_status;
            $aData = $order->fetchByMember($this->app->member_id,$nPage,$order_status);
        }

        $this->get_order_details($aData,'member_orders');
        $oImage = app::get('image')->model('image');
        $oGoods = app::get('b2c')->model('goods');
        $imageDefault = app::get('image')->getConf('image.set');
        $obj_payments_cfgs = app::get('ectools')->model('payment_cfgs');
        foreach($aData['data'] as $k => &$v) {
            foreach($v['goods_items'] as $k2 => &$v2) {
                $spec_desc_goods = $oGoods->getList('spec_desc',array('goods_id'=>$v2['product']['goods_id']));
                $select_spec_private_value_id = @reset($v2['product']['products']['spec_desc']['spec_private_value_id']);
                $spec_desc_goods = @reset($spec_desc_goods[0]['spec_desc']);
                if($spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']){
                    list($default_product_image) = explode(',', $spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']);
                    $v2['product']['thumbnail_pic'] = $default_product_image;
                }else{
                    if( !$v2['product']['thumbnail_pic'] && !$oImage->getList("image_id",array('image_id'=>$v['image_default_id']))){
                        $v2['product']['thumbnail_pic'] = $imageDefault['S']['default_image'];
                    }
                    $v2['product']['thumbnail_pic_src'] = base_storager::image_path($v2['product']['thumbnail_pic'], 's' );
                }
            }
            $v['goods_num'] = count($v['goods_items']);
            if ($v['payinfo']['pay_app_id']) {
               $aData['data'][$k]['payinfo']['display_name'] = $obj_payments_cfgs->get_app_display_name($v['payinfo']['pay_app_id']);
            }
        }

        foreach ($aData['data'] as $key => $value) {
            unset($aData['data'][$key]['goods_items']);
            $aData['data'][$key]['goods_items'] = array_values($value['goods_items']);
            if ($value['consignee']['area']) {
                $str = explode(':', $value['consignee']['area']);
                $aData['data'][$key]['consignee']['txt_area'] = str_replace('/','',$str[1]);
            }
        }
        $deliveryMdl=  app::get('b2c')->model('delivery');

       foreach ($aData['data'] as $key => $value) {
           $delivery=$deliveryMdl->getList('logi_name,logi_no',array('order_id'=>$value['order_id']));
           $dly= kernel::single('b2c_mdl_dlycorp') ->getList('corp_code',array('name'=>$delivery[0]['logi_name']));
           $aData['data'][$key]['logi_name']=$delivery[0]['logi_name'];
           $aData['data'][$key]['logi_no']=$delivery[0]['logi_no'];
           $aData['data'][$key]['corp_code']=$dly[0]['corp_code'];
       }

       foreach($aData['data'] as $key => $value){
           $is_opinions = 1;
            foreach($value['goods_items'] as $k=>$val){
                $goods = app::get('b2c')->model('goods')->getRow("*",array('goods_id'=>$val['product']['goods_id']));
                if(!$goods){
                    $aData['data'][$key]['goods_items'][$k]['product']['is_opinions'] = 1;
                    $val['product']['is_opinions'] = 1;
                    $aData['data'][$key]['goods_items'][$k]['product']['is_comment'] = 1;
                    $val['product']['is_comment'] = 1;
                }
                $brand = app::get('b2c')->model('brand')->get_brand_name_for_goods_id($val['product']['goods_id']);
                $aData['data'][$key]['goods_items'][$k]['product']['brand_name'] = $brand;
                if(!$val['product']['is_opinions'] && !$val['product']['is_comment']){
                    $is_opinions = 0;
                }
            }
            if($value['status']=="finish"){
                if($is_opinions == 1 ){
                    $aData['data'][$key]['is_opinions'] = 1;
                }else{
                    $aData['data'][$key]['is_opinions'] = 0;
                }
            }else{
                $aData['data'][$key]['is_opinions'] = 0;
            }
            $aData['data'][$key]['addon'] = unserialize($value['addon']);
        }
        usort($aData['data'], function($a, $b) {
            $al = $a['createtime'];
            $bl = $b['createtime'];
            return ($al > $bl) ? -1 : 1;
        });

        return $aData['data'];
    }


    //订单详情
    public function orderdetail($param = array())
    {
        $order_id = $param['order_id'];
        if (!isset($order_id) || !$order_id)
        {
            $this->app->rpcService->send_user_error('4003', '订单编号不能为空！');
        }

        $objOrder = app::get('b2c')->model('orders');
        $subsdf = array('order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))), 'order_pmt'=>array('*'));
        $sdf_order = $objOrder->dump($order_id, '*', $subsdf);
        $objMath = kernel::single("ectools_math");
        if(!$sdf_order||$this->app->member_id!=$sdf_order['member_id']){
            $this->app->rpcService->send_user_error('404', '订单号：'.$order_id.'不存在！');
        }
        if($sdf_order['member_id']){
            $member = app::get('b2c')->model('members');
            $aMember = $member->dump($sdf_order['member_id'], 'email');
            $sdf_order['receiver']['email'] = $aMember['contact']['email'];
        }

        // 处理收货人地区
        $arr_consignee_area = array();
        $arr_consignee_regions = array();
        if (strpos($sdf_order['consignee']['area'], ':') !== false)
        {
            $arr_consignee_area = explode(':', $sdf_order['consignee']['area']);
            if ($arr_consignee_area[1])
            {
                if (strpos($arr_consignee_area[1], '/') !== false)
                {
                    $arr_consignee_regions = explode('/', $arr_consignee_area[1]);
                }
            }

            $sdf_order['consignee']['area'] = (is_array($arr_consignee_regions) && $arr_consignee_regions) ? $arr_consignee_regions[0] . $arr_consignee_regions[1] . $arr_consignee_regions[2] : $sdf_order['consignee']['area'];
        }

        // 订单的相关信息的修改
        $obj_other_info = kernel::servicelist('b2c.order_other_infomation');
        if ($obj_other_info)
        {
            foreach ($obj_other_info as $obj)
            {
                $data['discount_html'] = $obj->gen_point_discount($sdf_order);
            }
        }
        $data['order'] = $sdf_order;

        $order_items = array();
        $gift_items = array();
        $this->get_order_detail_item($sdf_order,'member_order_detail');
        $data['order'] = $sdf_order;
// echo "<pre>";print_r($this->pagedata['order']);exit;
        /** 将商品促销单独剥离出来 **/
        if ($data['order']['order_pmt'])
        {
            foreach ($data['order']['order_pmt'] as $key=>$arr_pmt)
            {
                if ($arr_pmt['pmt_type'] == 'goods')
                {
                    $data['order']['goods_pmt'][$arr_pmt['product_id']][$key] =  $data['order']['order_pmt'][$key];
                    unset($data['order']['order_pmt'][$key]);
                }
            }
        }
        /** end **/

        // 得到订单留言.
        $oMsg = kernel::single("b2c_message_order");
        $arrOrderMsg = $oMsg->getList('*', array('order_id' => $order_id, 'object_type' => 'order'), $offset=0, $limit=-1, 'time DESC');

        $data['ordermsg'] = $arrOrderMsg;

        //我已付款
        $$timeHours = array();
        for($i=0;$i<24;$i++){
            $v = ($i<10)?'0'.$i:$i;
            $timeHours[$v] = $v;
        }
        $timeMins = array();
        for($i=0;$i<60;$i++){
            $v = ($i<10)?'0'.$i:$i;
            $timeMins[$v] = $v;
        }
        $data['timeHours'] = $timeHours;
        $data['timeMins'] = $timeMins;

        // 生成订单日志明细
        //$oLogs =$this->app->model('order_log');
        //$arr_order_logs = $oLogs->getList('*', array('rel_id' => $order_id));
        $arr_order_logs = $objOrder->getOrderLogList($order_id);

        // 取到支付单信息
        $obj_payments = app::get('ectools')->model('payments');
        //$data['paymentlists'] = $obj_payments->get_payments_by_order_id($order_id);

        // 支付方式的解析变化
        $obj_payments_cfgs = app::get('ectools')->model('payment_cfgs');
        $arr_payments_cfg = $obj_payments_cfgs->getPaymentInfo($data['order']['payinfo']['pay_app_id']);
        $data['order']['payment'] = $arr_payments_cfg;

        #//物流跟踪安装并且开启
        #$logisticst = app::get('b2c')->getConf('system.order.tracking');
        #$logisticst_service = kernel::service('b2c_change_orderloglist');
        #if(isset($logisticst) && $logisticst == 'true' && $logisticst_service){
        #    $this->pagedata['services']['logisticstack'] = $logisticst_service;
        #}
        $data['orderlogs'] = $arr_order_logs['data'];
        $data['time_now'] = time();
        // 添加html埋点
        foreach( kernel::servicelist('b2c.order_add_html') as $services ) {
            if ( is_object($services) ) {
                if ( method_exists($services, 'fetchHtml') ) {
                    $services->fetchHtml($this,$order_id,'site/invoice_detail.html');
                }
            }
        }

        return $data;
    }

    /**
     * 得到订单列表详细
     * @param array 订单详细信息
     * @param string tpl
     * @return null
     */
    protected function get_order_details(&$aData,$tml='member_orders')
    {
        if (isset($aData['data']) && $aData['data'])
        {
            $objMath = kernel::single('ectools_math');
            // 所有的goods type 处理的服务的初始化.
            $arr_service_goods_type_obj = array();
            $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
            foreach ($arr_service_goods_type as $obj_service_goods_type)
            {
                $goods_types = $obj_service_goods_type->get_goods_type();
                $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
            }

            foreach ($aData['data'] as &$arr_data_item)
            {
                $this->get_order_detail_item($arr_data_item,$tml);
            }
        }
    }

    /**
     * 得到订单列表详细
     * @param array 订单详细信息
     * @param string 模版名称
     * @return null
     */
    protected function get_order_detail_item(&$arr_data_item,$tpl='member_order_detail')
    {
        if (isset($arr_data_item) && $arr_data_item)
        {
            $objMath = kernel::single('ectools_math');
            // 所有的goods type 处理的服务的初始化.
            $arr_service_goods_type_obj = array();
            $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
            foreach ($arr_service_goods_type as $obj_service_goods_type)
            {
                $goods_types = $obj_service_goods_type->get_goods_type();
                $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
            }


            $arr_data_item['goods_items'] = array();
            $obj_specification = app::get('b2c')->model('specification');
            $obj_spec_values = app::get('b2c')->model('spec_values');
            $obj_goods = app::get('b2c')->model('goods');
            $oImage = app::get('image')->model('image');
            $obj_tip=app::get('b2c')->model('goods_tip');

            if (isset($arr_data_item['order_objects']) && $arr_data_item['order_objects'])
            {
                foreach ($arr_data_item['order_objects'] as $k=>$arr_objects)
                {
                    $index = 0;
                    $index_adj = 0;
                    $index_gift = 0;
                    $image_set = app::get('image')->getConf('image.set');
                    if ($arr_objects['obj_type'] == 'goods')
                    {
                        $tip_id=$obj_goods->getRow('tip_id',array('goods_id'=>$arr_objects['goods_id']));
                        $arr_data_item['order_objects'][$k]['tip_info']=$obj_tip->getRow('*',array('tip_id'=>$tip_id['tip_id']));
                        foreach ($arr_objects['order_items'] as $arr_items)
                        {
                            if (!$arr_items['products'])
                            {
                                $o = app::get('b2c')->model('order_items');
                                $tmp = $o->getList('*', array('item_id'=>$arr_items['item_id']));
                                $arr_items['products']['product_id'] = $tmp[0]['product_id'];
                            }

                            if ($arr_items['item_type'] == 'product')
                            {
                                if ($arr_data_item['goods_items'][$k]['product'])
                                    $arr_data_item['goods_items'][$k]['product']['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k]['product']['quantity']));
                                else
                                    $arr_data_item['goods_items'][$k]['product']['quantity'] = $arr_items['quantity'];

                                $arr_data_item['goods_items'][$k]['product'] = $arr_items;
                                $arr_data_item['goods_items'][$k]['product']['name'] = $arr_items['name'];
                                $arr_data_item['goods_items'][$k]['product']['goods_id'] = $arr_items['goods_id'];
                                $arr_data_item['goods_items'][$k]['product']['price'] = $arr_items['price'];
                                $arr_data_item['goods_items'][$k]['product']['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k]['product']['quantity']);
                                $arr_data_item['goods_items'][$k]['product']['amount'] = $arr_items['amount'];
                                $arr_goods_list = $obj_goods->getList('image_default_id,spec_desc', array('goods_id' => $arr_items['goods_id']));
                                $arr_goods = $arr_goods_list[0];
                                // 获取货品关联第一张图片
                                $select_spec_private_value_id = @reset($arr_items['products']['spec_desc']['spec_private_value_id']);
                                $spec_desc_goods = @reset($arr_goods['spec_desc']);
                                if($spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']){
                                    list($default_product_image) = explode(',', $spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']);
                                    $arr_goods['image_default_id'] = $default_product_image;
                                }else{
                                    if( !$arr_goods['image_default_id'] && !$oImage->getList("image_id",array('image_id'=>$arr_goods['image_default_id']))){
                                        $arr_goods['image_default_id'] = $image_set['S']['default_image'];
                                    }
                                }

                                $arr_data_item['goods_items'][$k]['product']['thumbnail_pic'] = $arr_goods['image_default_id'];
                                $arr_data_item['goods_items'][$k]['product']['thumbnail_pic_src'] = base_storager::image_path($arr_goods['image_default_id'], 's' );
                                if ($arr_items['addon'])
                                {
                                    $arrAddon = $arr_addon = unserialize($arr_items['addon']);
                                    if ($arr_addon['product_attr'])
                                        unset($arr_addon['product_attr']);
                                    $arr_data_item['goods_items'][$k]['product']['minfo'] = $arr_addon;
                                }else{
                                    unset($arrAddon,$arr_addon);
                                }
                                if ($arrAddon['product_attr'])
                                {
                                    foreach ($arrAddon['product_attr'] as $arr_product_attr)
                                    {
                                        $arr_data_item['goods_items'][$k]['product']['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                    }
                                }

                                if (isset($arr_data_item['goods_items'][$k]['product']['attr']) && $arr_data_item['goods_items'][$k]['product']['attr'])
                                {
                                    if (strpos($arr_data_item['goods_items'][$k]['product']['attr'], " ") !== false)
                                    {
                                        $arr_data_item['goods_items'][$k]['product']['attr'] = substr($arr_data_item['goods_items'][$k]['product']['attr'], 0, strrpos($arr_data_item['goods_items'][$k]['product']['attr'], $this->app->_(" ")));
                                    }
                                }
                            }
                            elseif ($arr_items['item_type'] == 'adjunct')
                            {
                                $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_items['item_type']];
                                $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);


                                if ($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj])
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity']));
                                else
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity'] = $arr_items['quantity'];

                                if (!$arrGoods['image_default_id'])
                                {
                                    $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                }
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj] = $arr_items;
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['name'] = $arr_items['name'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['quantity']);
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['goods_id'] = $arr_items['goods_id'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['price'] = $arr_items['price'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['link_url'] = $arrGoods['link_url'];
                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['amount'] = $arr_items['amount'];

                                if ($arr_items['addon'])
                                {
                                    $arr_addon = unserialize($arr_items['addon']);

                                    if ($arr_addon['product_attr'])
                                    {
                                        foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                        {
                                            $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                        }
                                    }
                                }

                                if (isset($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr']) && $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'])
                                {
                                    if (strpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], $this->app->_(" ")) !== false)
                                    {
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'] = substr($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], 0, strrpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_adj]['attr'], $this->app->_(" ")));
                                    }
                                }

                                $index_adj++;
                            }
                            else
                            {
                                // product gift.
                                if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                                {
                                    $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_items['item_type']];
                                    $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);

                                    if ($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift])
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']));
                                    else
                                        $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity'] = $arr_items['quantity'];

                                    if (!$arrGoods['image_default_id'])
                                    {
                                        $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                    }
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift] = $arr_items;
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['name'] = $arr_items['name'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['goods_id'] = $arr_items['goods_id'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['price'] = $arr_items['price'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['score'] = intval($arr_items['score']*$arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['quantity']);
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['link_url'] = $arrGoods['link_url'];
                                    $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['amount'] = $arr_items['amount'];

                                    if ($arr_items['addon'])
                                    {
                                        $arr_addon = unserialize($arr_items['addon']);

                                        if ($arr_addon['product_attr'])
                                        {
                                            foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                            {
                                                $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                            }
                                        }
                                    }

                                    if (isset($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr']) && $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'])
                                    {
                                        if (strpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], $this->app->_(" ")) !== false)
                                        {
                                            $arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'] = substr($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], 0, strrpos($arr_data_item['goods_items'][$k][$arr_items['item_type'].'_items'][$index_gift]['attr'], $this->app->_(" ")));
                                        }
                                    }
                                }
                                $index_gift++;
                            }
                        }
                    }
                    else
                    {
                        if ($arr_objects['obj_type'] == 'gift')
                        {
                            if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                            {
                                foreach ($arr_objects['order_items'] as $arr_items)
                                {
                                    if (!$arr_items['products'])
                                    {
                                        $o = $this->app->model('order_items');
                                        $tmp = $o->getList('*', array('item_id'=>$arr_items['item_id']));
                                        $arr_items['products']['product_id'] = $tmp[0]['product_id'];
                                    }

                                    $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_objects['obj_type']];
                                    $str_service_goods_type_obj->get_order_object(array('goods_id' => $arr_items['goods_id'], 'product_id'=>$arr_items['products']['product_id']), $arrGoods,$tpl);

                                    if (!isset($arr_items['products']['product_id']) || !$arr_items['products']['product_id'])
                                        $arr_items['products']['product_id'] = $arr_items['goods_id'];

                                    if ($arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']])
                                        $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity'] = $objMath->number_plus(array($arr_items['quantity'], $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']));
                                    else
                                        $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity'] = $arr_items['quantity'];

                                    if (!$arrGoods['image_default_id'])
                                    {
                                        $arrGoods['image_default_id'] = $image_set['S']['default_image'];
                                    }

                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['name'] = $arr_items['name'];
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['goods_id'] = $arr_items['goods_id'];
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['price'] = $arr_items['price'];
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['thumbnail_pic'] = $arrGoods['image_default_id'];
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['point'] = intval($arr_items['score']*$arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['quantity']);
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['nums'] = $arr_items['quantity'];
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['link_url'] = $arrGoods['link_url'];
                                    $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['amount'] = $arr_items['amount'];

                                    if ($arr_items['addon'])
                                    {
                                        $arr_addon = unserialize($arr_items['addon']);

                                        if ($arr_addon['product_attr'])
                                        {
                                            foreach ($arr_addon['product_attr'] as $arr_product_attr)
                                            {
                                                $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'] .= $arr_product_attr['label'] . $this->app->_(":") . $arr_product_attr['value'] . $this->app->_(" ");
                                            }
                                        }
                                    }

                                    if (isset($arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr']) && $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'])
                                    {
                                        if (strpos($arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], $this->app->_(" ")) !== false)
                                        {
                                            $arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'] = substr($arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], 0, strrpos($arr_data_item[$arr_items['item_type'].'_items'][$arr_items['products']['product_id']]['attr'], $this->app->_(" ")));
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if ($arr_service_goods_type_obj[$arr_objects['obj_type']])
                            {

                                $str_service_goods_type_obj = $arr_service_goods_type_obj[$arr_objects['obj_type']];
                                $arr_data_item['extends_items'][] = $str_service_goods_type_obj->get_order_object($arr_objects, $arr_Goods,$tpl);
                            }
                        }
                    }
                }
            }

        }
    }

   /**
     * 用户取消订单
     * @params string order id
     * @return null
     */
    public function cancel($param = array())
    {
        $order_id = $param['order_id'];
        $this->member = $this->get_current_member();
        $objM = app::get('b2c')->model('orders');
        $order = $objM->getRow('status,pay_status,ship_status',array('order_id'=>$order_id,'member_id'=>$this->member['member_id']));
        if(!$order){
            $this->app->rpcService->send_user_error('4003', '您无权进行此操作');
        }
        $obj_checkorder = kernel::service('b2c_order_apps', array('content_path'=>'b2c_order_checkorder'));
        if (!$obj_checkorder->check_order_cancel($order_id,'',$message))
        {
            $this->app->rpcService->send_user_error('4003', $message);
        }

        $sdf['order_id'] = $order_id;
        $sdf['op_id'] = $this->member['member_id'];
        $sdf['opname'] = $this->member['uname'];
        $sdf['account_type'] = $this->member['account_type'];

        $b2c_order_cancel = kernel::single("b2c_order_cancel");
        if ($b2c_order_cancel->generate($sdf))
        {
             return '操作成功';
        }
        else
        {
            $this->app->rpcService->send_user_error('4003', '参数错误');
        }
    }

    //收货地址
    public function receiver(){
        $objMem = app::get('b2c')->model('members');
        return $objMem->getMemberAddr($this->app->member_id);
    }

    /*
     * 设置和取消默认地址，$disabled 2为设置默认1为取消默认
     */
    public function set_default($filter){
        $addrId = $filter['addr_id'];
        $disabled = $filter['disabled'];
        if(!$addrId) $this->app->rpcService->send_user_error('4003', '参数错误');
        $obj_member = app::get('b2c')->model('members');
        $member_id = $this->app->member_id;
        if($obj_member->check_addr($addrId,$member_id)){
            if($obj_member->set_to_def($addrId,$member_id,$message,$disabled)){
                return '操作成功';
            }else{
                $this->app->rpcService->send_user_error('4003', $message);
            }
        }else{
            $this->app->rpcService->send_user_error('4003', '参数错误');
        }
    }

    /*
     *添加、修改收货地址
     * */
    public function modify_receiver($filter){
    	$addrId = $filter['addr_id'];
        if(!$addrId){
            $this->app->rpcService->send_user_error('4003', '参数错误');
        }
        $obj_member = app::get('b2c')->model('members');
        if($obj_member->check_addr($addrId,$this->app->member_id)){
            if($aRet = $obj_member->getAddrById($addrId)){
                $aRet['defOpt'] = array('0'=>app::get('b2c')->_('否'), '1'=>app::get('b2c')->_('是'));
                return $aRet;
            }else{
            	$this->app->rpcService->send_user_error('4003', '修改的收货地址不存在！');
            }
        }else{
            $this->app->rpcService->send_user_error('4003', '参数错误');
        }
    }

    /*
     *获取地址数据
     * */
    public function get_regions(){

    	/*
    	$where = intval($_POST['p_region_id']) > 0?'r.p_region_id='.intval($_POST['p_region_id']):'r.p_region_id IS NULL';

    	$sql="select region_id,local_name,(select count(*) from sdb_ectools_regions where p_region_id=r.region_id) as child_count from sdb_ectools_regions as r where ".$where." order by ordernum asc,region_id asc";
    	$rows = kernel::database()->select($sql);

    	 return $rows;

    	*/

    	$this->getAllRegions('','',$region_count, $regions);
        $arr = array();
        foreach($regions as $v) {
            $arr[] = $v;
        }
        unset($this->regions);
        return $arr;
    }

    private function getAllRegions($p_regionid='', $pkey='', &$region_count=array(), &$regions){
        $show_depth = app::get('ectools')->getConf('system.area_depth');
        if ($p_regionid)
            $sql="select region_id,region_grade,local_name,ordernum,(select count(*) from sdb_ectools_regions where p_region_id=r.region_id) as child_count from sdb_ectools_regions as r where r.p_region_id=".intval($p_regionid)." order by ordernum asc,region_id";
        else
            $sql="select region_id,region_grade,local_name,ordernum,(select count(*) from sdb_ectools_regions where p_region_id=r.region_id) as child_count from sdb_ectools_regions as r where r.p_region_id is null order by ordernum asc,region_id";

        $row = kernel::database()->select($sql);

        if (isset($row) && $row)
        {
            $cur_row = current($row);
            if(!$region_count[$cur_row['region_grade']]) {
                $start_index = 0;
            }
            else {
                $start_index = $region_count[$cur_row['region_grade']];
            }
            foreach ($row as $key => $val)
            {
                $tmp = array(
                    $val['local_name'],
                    $val['region_id'],
                );
                $index = $pkey!==''?$pkey:$key;
                if($val['child_count']) {
                    if($val['region_grade']<$show_depth) {
                        $tmp[] = $start_index;
                    }
                    $start_index++;
                    $region_count[$cur_row['region_grade']] = $start_index;
                }
                if($val['region_grade'] != 1) {
                    $regions[$val['region_grade']][$index][] = implode(":", $tmp);
                }
                else {
                    $regions[$val['region_grade']][$index] = implode(":", $tmp);
                }
                if ($val['child_count'] && $val['region_grade']<$show_depth) {
                    $this->getAllRegions($val['region_id'], $start_index-1, $region_count, $regions);
                }
            }
        }
    }

    public function set_identity(){
        if ($_POST) {
            $rname = $_POST['rname'];
         $identity = $_POST['identity'];
         $member_id = $this->app->member_id;

          if(kernel::database()->exec("update sdb_b2c_members set `identity` = '{$identity}' ,`rname` = '{$rname}' where member_id = '{$member_id}'")){
            return '1';
          }
          return '0';
        }


    }


    /*
     *保存收货地址
     * */
    public function save_rec($filter){
        //return $_FILES['file']['name'].'llll';exit();
        if(!$filter['def_addr']){
            $filter['def_addr'] = 0;
        }

        // $image1 = $this->imageUpload1();

        // $image2 = $this->imageUpload2();

        $arr = $filter;

        // $arr['image_id1'] = $image1['image_id'];
        // $arr['image_id2'] = $image2['image_id'];



        $save_data = kernel::single('b2c_member_addrs')->purchase_save_addr($arr,$this->app->member_id,$msg);



               // kernel::single('b2c_member_addrs')->update( $_data, array( 'member_id' => $this->app->member_id ));

        if(!$save_data){
             $this->app->rpcService->send_user_error('4003', $msg);
        }
        $this->app->rpcService->send_user_success('保存成功',$save_data['addr_id']);
    }

    //添加收货地址
    public function add_receiver(){
        $obj_member = app::get('b2c')->model('members');
        if($obj_member->isAllowAddr($this->app->member_id)){
        	return true;
        }else{
        	$this->app->rpcService->send_user_error('4003', '最多添加10个收货地址');
        }
    }

    //删除收货地址
    public function del_rec(){
    	$addrId = $_POST['addr_id'];
        if(!$addrId) $this->app->rpcService->send_user_error('4003', '参数错误');
        $obj_member = app::get('b2c')->model('members');
        if($obj_member->check_addr($addrId,$this->app->member_id))
        {
            if($obj_member->del_rec($addrId,$message,$this->app->member_id))
            {
                return true;
            }
            else
            {
                $this->app->rpcService->send_user_error('4003', $message);
            }
        }
        else
        {
            $this->app->rpcService->send_user_error('4003', '操作失败');
        }
    }

    public function coupon($filter,$svservice='',$coupon_code='') {
    	$nPage = $filter['n_page'] ? $filter['n_page'] : 1;
        $oCoupon = kernel::single('b2c_coupon_mem');
		if(empty($coupon_code)){
        	$aData = $oCoupon->get_list_m($this->app->member_id,$filter);
		}else{
			$aData = $oCoupon->get_list_m($this->app->member_id,array('memc_code'=>$coupon_code));
		}


        if ($aData) {
            $this->member = kernel::single('b2c_user_object')->get_members_data(array('members'=>'member_lv_id'));
            foreach ($aData as $k => $item) {
                if ($item['coupons_info']['cpns_status'] !=1) {
                    $aData[$k]['coupons_info']['cpns_status'] = false;
                    $aData[$k]['memc_status'] = app::get('b2c')->_('此种优惠券已取消');
                    continue;
                }

                $member_lvs = explode(',',$item['time']['member_lv_ids']);
                if (!in_array($this->member['members']['member_lv_id'],(array)$member_lvs)) {
                    $aData[$k]['coupons_info']['cpns_status'] = false;
                    $aData[$k]['memc_status'] = app::get('b2c')->_('本级别不准使用');
                    continue;
                }

                $curTime = time();
                if ($curTime>=$item['time']['from_time'] && $curTime<$item['time']['to_time']) {
                    if ($item['memc_used_times']<app::get('b2c')->getConf('coupon.mc.use_times')){
                        if ($item['coupons_info']['cpns_status']){
                            $aData[$k]['memc_status'] = app::get('b2c')->_('可使用');
                        }else{
                            $aData[$k]['coupons_info']['cpns_status'] = false;
                            $aData[$k]['memc_status'] = app::get('b2c')->_('本优惠券已作废');
                        }
                    }else{
                        $aData[$k]['coupons_info']['cpns_status'] = false;
                        $aData[$k]['memc_status'] = app::get('b2c')->_('本优惠券次数已用完');
                    }
                }else{
                    $aData[$k]['coupons_info']['cpns_status'] = false;
                    $aData[$k]['memc_status'] = app::get('b2c')->_('还未开始或已过期');
                }
            }
        }

        //$aData = $oCoupon->get_list_m($this->app->member_id);

		$mdl_sales_rule_order=app::get('b2c')->model('sales_rule_order');
		foreach($aData as $k=>&$coupon_item){
			$coupon_item['rule_info']=$mdl_sales_rule_order->getRow('*',array('rule_id'=>$coupon_item['coupons_info']['rule']['rule_id']));

                        $aData[$k]["rule_info"]['name'] = str_replace("优惠劵规则-", "", $coupon_item['rule_info']['name']);
			if(isset($coupon_item['rule_info']['action_solution']['b2c_promotion_solutions_byfixed'])){
				$coupon_item['rule_info']['discount_type']='byfixed';
				$coupon_item['rule_info']['discount_value']=$coupon_item['rule_info']['action_solution']['b2c_promotion_solutions_byfixed']['total_amount'];
			}else if(isset($coupon_item['rule_info']['action_solution']['b2c_promotion_solutions_topercent'])){
				$coupon_item['rule_info']['discount_type']='topercent';
				$coupon_item['rule_info']['discount_value']=$coupon_item['rule_info']['action_solution']['b2c_promotion_solutions_topercent']['percent'];
			}else{
				$coupon_item['rule_info']['discount_type']='others';
				$coupon_item['rule_info']['discount_value']=$coupon_item['rule_info']['action_solution'];
			}
		}



        return $aData;
    }

     function get_invc_s(){
        $code=app::get('b2c')->model('member_invc')->getList('code',array('has'=>'false','member_id'=>$this->app->member_id,'has_op'=>'3'));
        $code1=app::get('b2c')->model('member_invc')->getList('code',array('member_id'=>$this->app->member_id));
         if(count($code)==count($code1)){
            return '1';
         }
         return '0';
     }

     public function get_invc(){


        if($_POST['num']){
         $arr_m_c= $this->get_sjs($_POST['num']);

        $data = array();


         for($i=0;$i<count($arr_m_c);$i++)
         {
            $data[$i]['member_id'] = $this->app->member_id;
            $data[$i]['time'] = time();
            $data[$i]['code'] = $arr_m_c[$i];

            app::get('b2c')->model('member_invc')->save($data[$i]);
         }
          $this->app->rpcService->send_user_error('4003', '邀请码申请已提交,请等待审核！');

       }

           $mdl = app::get('b2c')->model('member_invc');

            $code=$mdl->getList('code_id,memc_isvalid,code',array('member_id'=>$this->app->member_id,'has_op'=>'3'));
            $code1=$mdl->getList('code_id,memc_isvalid,code',array('member_id'=>$this->app->member_id,'has_op'=>'1'));
            $code2=$mdl->getList('code_id,memc_isvalid,code',array('member_id'=>$this->app->member_id));
            if(count($code1)==count($code2)&&count($code2)!=0){
                $this->app->rpcService->send_user_error('4003', '您的邀请码正在审核中');
            }

           $a = $this->get_invc_s();
           if ($a=='1') {

               $mdl->delete(array('member_id' => $this->app->member_id));
               return array();
           }

            if (count($code)==0) {
                return array();
            }










         return $code;



     }


     public function get_invc_x(){


        if($_POST['num']){
         $arr_m_c= $this->get_sjs($_POST['num']);

        $data = array();


         for($i=0;$i<count($arr_m_c);$i++)
         {
            $data[$i]['member_id'] = $this->app->member_id;
            $data[$i]['time'] = time();
            $data[$i]['code'] = $arr_m_c[$i];

            app::get('b2c')->model('member_invc')->save($data[$i]);
         }
          $this->app->rpcService->send_user_error('4003', '邀请码申请已提交,请等待审核！');

       }

           $mdl = app::get('b2c')->model('member_invc');


            $code1=$mdl->getList('code_id,memc_isvalid,code,has',array('member_id'=>$this->app->member_id,'has_op'=>'1'));
            $code2=$mdl->getList('code_id,memc_isvalid,code',array('member_id'=>$this->app->member_id));
            if(count($code1)==count($code2)&&count($code2)!=0){
                $this->app->rpcService->send_user_error('4003', '您的邀请码正在审核中');
            }

           $a = $this->get_invc_s();
           if ($a=='1') {

               $mdl->delete(array('member_id' => $this->app->member_id));
               return array();
           }

            if (count($code1)==0) {
                return array();
            }










         return $code1;



     }


     function download(){
        return 'http://www.belly-cut.com.cn/index.php/wap/gallery-xiazai.html';
     }




    function get_sjs($num){
        $no_of_codes = $num;
       $exclude_codes_array='';
       $code_length = 6;
       $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
       $promotion_codes = array();
    for($j = 0 ; $j < $no_of_codes; $j++){

        $code = "";
      for ($i = 0; $i < $code_length; $i++){

        $code .= $characters[mt_rand(0, strlen($characters)-1)];
        }

         if(!in_array($code,$promotion_codes)){

             if(is_array($exclude_codes_array)){

                if(!in_array($code,$exclude_codes_array)){

                    $promotion_codes[$j] = $code;
                    }
                 else{
                     $j--;
                 }
           }
            else{
            $promotion_codes[$j] = $code;
            }
            }
    else{

        $j--;
        }
    }
    return $promotion_codes;
}



    /*
     *发送站内信
     * */
    public function send_msg(){
        if(!isset($_POST['msg_to']) || $_POST['msg_to'] == '管理员'){
            $_POST['to_type'] = 'admin';
            $_POST['msg_to'] = 0;
        }else{
            $userObject = kernel::single('b2c_user_object');
            $to_id = $userObject->get_id_by_uname($_POST['msg_to']);
            if(!$to_id){
                $this->splash('failed',null,app::get('b2c')->_('收件人不存在'),$_POST['response_json']);
            }
            $_POST['to_id'] = $to_id;
        }
        if($_POST['subject'] && $_POST['comment']) {
            $objMessage = kernel::single('b2c_message_msg');
            $_POST['has_sent'] = $_POST['has_sent'] == 'false' ? 'false' : 'true';
            $_POST['member_id'] = $this->app->member_id;
            $_POST['uname'] = $this->member['uname'];
            $_POST['contact'] = $_POST['contact'];
            $_POST['ip'] = $_SERVER["REMOTE_ADDR"];
            $_POST['subject'] = strip_tags($_POST['subject']);
            $_POST['comment'] = strip_tags($_POST['comment']);
            if($_POST['comment_id']){
                //$data['comment_id'] = $_POST['comment_id'];
                $_POST['comment_id'] = '';//防止用户修改comment_id
            }
            if( $objMessage->send($_POST) ) {
            if($_POST['has_sent'] == 'false'){
                return true;
            }else{
                return true;
            }
            } else {
                $this->app->rpcService->send_user_error('4003', '发送失败');
            }
        }
        else {
            $this->app->rpcService->send_user_error('4003', '必填项不能为空');
        }
    }

	/*
        过滤POST来的数据,基于安全考虑,会把POST数组中带HTML标签的字符过滤掉
    */
    private function check_input($data)
    {
        $aData = $this->arrContentReplace($data);
        return $aData;
    }

    private function arrContentReplace($array)
    {
        if (is_array($array)){
            foreach($array as $key=>$v){
                $array[$key] =     $this->arrContentReplace($array[$key]);
            }
        }
        else{
            $array = strip_tags($array);
        }
        return $array;
    }

    /**
     * 关注会员
     */
    function follow( $param = array(), $rpcService ) {
        if ( $param['member_id'] > 0 && $param['follow_id'] > 0 ) {
            $mdl    = app::get('b2c')->model('member_follow');
            $data   = array (
                'member_id' => $param['member_id'],
                'follow_id' => $param['follow_id'],
            );
            $list   = $mdl->getList('*', $data);
            if ( $list ) {
                $ret    = array (
                    'code'  => -2,
                    'msg'   => app::get('b2c')->_('已关注过了,请勿重复关注'),
                );
            } else {
                $data['addtime']    = time();
                if ( $mdl->save($data) ) {
                    $this->update_follow_fans_num($data, $rpcService);
                    $ret    = array (
                        'code'  => 1,
                        'data'  => $data,
                        'msg'   => app::get('b2c')->_('关注成功'),
                    );
                } else {
                    $ret    = array (
                        'code'  => -4,
                        'msg'   => app::get('b2c')->_('系统错误,请联系管理员'),
                    );
                }
            }
        } else {
            $ret    = array (
                'code'  => -1,
                'msg'   => app::get('b2c')->_('会员ID或关注的用户ID不合法'),
            );
        }
        if ( $ret['code'] < 0 ) {
            $rpcService->send_user_error($ret['code'], $ret['msg']);
        }
        return $ret;
    }

    /**
     * 取消关注
     */
    function unfollow( $param = array(), $rpcService ) {
        if ( $param['member_id'] > 0 && $param['follow_id'] > 0 ) {
            $mdl    = app::get('b2c')->model('member_follow');
            $data   = array (
                'member_id' => $param['member_id'],
                'follow_id' => $param['follow_id'],
            );
            $list   = $mdl->getList('*', $data);
            if ( $list ) {
                if ( $mdl->delete($data) ) {
                    $data['type'] = 'delete';
                    $this->update_follow_fans_num($data, $rpcService);
                    $ret    = array (
                        'code'  => 1,
                        'data'  => $data,
                        'msg'   => app::get('b2c')->_('取消关注成功'),
                    );
                }
            } else {
                $ret    = array (
                    'code'  => -2,
                    'msg'   => app::get('b2c')->_('未关注过该用户'),
                );
            }
        } else {
            $ret    = array (
                'code'  => -1,
                'msg'   => app::get('b2c')->_('会员ID或关注的用户ID不合法'),
            );
        }
        if ( $ret['code'] < 0 ) {
            $rpcService->send_user_error($ret['code'], $ret['msg']);
        }
        return $ret;
    }

    /**
     * 更新关注/粉丝人数
     */
    function update_follow_fans_num( $param = array(), $rpcService ) {
        $mdl    = app::get('b2c')->model('members');
        $_type  = $param['type'] ? $param['type'] : 'add';
        $filter = array (
            'member_id' => array($param['member_id'], $param['follow_id'])
        );
        $list   = $mdl->getList('follow_num, fans_num, member_id', $filter);
        if ( $list ) {
            foreach ( $list AS $v ) {
                $fields = $v['member_id'] == $param['member_id'] ? 'follow_num' : 'fans_num';
                $_data  = array (
                    $fields => $_type == 'add' ? $v[$fields] + 1 : $v[$fields] - 1,
                );
                $mdl->update( $_data, array( 'member_id' => $v['member_id'] ));
            }
        }
        $ret    = array (
            'code'  => 1,
            'msg'   => app::get('b2c')->_('更新成功'),
        );
        return $ret;
    }

    /**
     * 我要开店
     */
    function open_shop( $param = array(), $rpcService ) {

        if ( $param['member_id'] > 0 && trim($param['agency_id']) && trim($param['shop_name']) ) {
            $data   = array (
                'member_id' => $param['member_id'],
            );
            $mdl    = app::get('microshop')->model('shop');
            $info   = $mdl->getList('*', $data);
            if ( $info ) {
                $ret    = array (
                    'code'  => -2,
                    'msg'   => app::get('b2c')->_('已经开过微店了,请勿重复操作'),
                );
            } else {
                $_filter    = array (
//                     'member_id' => $param['agency_id'],
                	'agency_no' => trim($param['agency_id']), //更新为经销商编号
                    'member_type'   => 3,
                );
                $m_mdl  = app::get('b2c')->model('members');
                $_row   = $m_mdl->dump($_filter);
                if ( isset($_row['member_id']) && $_row['member_id'] > 0 ) {
                    $data['agency_id']  = $_row['member_id'];
                    $data['shop_name']  = trim($param['shop_name']);
                    $data['addtime']    = time();

                    if ( $mdl->save($data) ) {
                        $_data  = array (
                                'member_type'   => 2,
                                );
                        // 修改用户状态
                        app::get('b2c')->model('members')->update($_data, array('member_id' => $param['member_id']));
                        $ret    = array (
                                'code'  => 1,
                                'data'  => $data,
                                'msg'   => app::get('b2c')->_('开店成功'),
                                );
                    } else {
                        $ret    = array (
                                'code'  => -3,
                                'msg'   => app::get('b2c')->_('系统错误,请联系管理员'),
                                );
                    }
                } else {
                    $ret    = array (
                        'code'  => -4,
                        'msg'   => app::get('b2c')->_('邀请您开店者的手机号错误'),
                    );
                }
            }
        } else {
            $ret    = array (
                'code'  => -1,
                'msg'   => app::get('b2c')->_('请确保会员ID/开店者的手机号/微店名称都合法'),
            );
        }
        if ( $ret['code'] < 0 ) {
            $rpcService->send_user_error($ret['code'], $ret['msg']);
        }
        return $ret;
    }

    /**
     * 获得经销商
     */
    function get_agency() {
        $mdl    = app::get('b2c')->model('members');
        $filter = array (
            'member_type'   => 2,
        );
        return $mdl->getList('*', $filter, 0, -1);
    }

    /**
     * 获得关注列表
     */
    function get_follow($param = array(), $rpcService) {
        $member_id  = intval($param['member_id']);
        if ( $member_id > 0 ) {
            $page   = intval($request['page_no']);
            $page   = $page > 0 ? $page : 1;
    	    $db     = kernel::database();
            $filter = array (
                'member_id' => $member_id,
            );
            $sql    = 'SELECT count(*) AS sum FROM '.$db->prefix.'b2c_member_follow AS mf LEFT JOIN '.$db->prefix.'microshop_shop AS s ON s.member_id = mf.follow_id WHERE mf.member_id = '.$member_id.' AND s.is_open = 1';
            $count  = $db->selectRow($sql);
            $list   = array();
            if ( $count['sum'] ) {
                $page_size  = intval($param['page_size']);
                $page_size  = $page_size > 0 ? $page_size : 20;
                $order      = trim($param['order']);
                $order      = $order ? $order : 'mf.addtime';
                $order_type = trim($param['order_type']);
                $order_type = $order_type ? $order_type : 'DESC';
                $orderby    = ' ORDER BY '.$order.' '.$order_type;
                $offset     = ($page - 1) * $page_size;
                //$sql        = 'SELECT m.avatar, m.cover, m.follow_num, m.fans_num, s.* FROM '.$db->prefix.'b2c_member_follow AS mf LEFT JOIN '.$db->prefix.'b2c_members AS m ON m.member_id = mf.follow_id LEFT JOIN '.$db->prefix.'microshop_shop AS s ON s.member_id = mf.follow_id WHERE mf.member_id = '.$member_id.' AND s.is_open = 1'.$orderby;
                $sql        = 'SELECT s.* FROM '.$db->prefix.'b2c_member_follow AS mf LEFT JOIN '.$db->prefix.'microshop_shop AS s ON s.member_id = mf.follow_id WHERE mf.member_id = '.$member_id.' AND s.is_open = 1'.$orderby;
                $list       = $db->selectLimit($sql, $page_size, $offset);
                if ( $list ) {
                    $m_mdl  = app::get('b2c')->model('members');
                    foreach ( $list AS $k => $v ) {
                        $m_info = $m_mdl->dump($v['member_id']);
                        $list[$k]['avatar'] = $m_info['avatar'] ? base_storager::image_path($m_info['avatar'],'l') : kernel::get_resource_host_url()."/headPlaceHolder_big@2x.png";
                        $list[$k]['cover'] = $m_info['cover'] ? kernel::single('base_storager')->image_path($m_info['cover']) : $this->app->res_url.'/images/top-bg.png';
                        $_param = array (
                            'app'   => 'microshop',
                            'ctl'   => 'site_index',
                            'full'  => 1,
                            'act'   => 'detail',
                            'arg0'  => $v['shop_id'],
                        );
                        $list[$k]['shop_link']  = app::get('site')->router()->gen_url($_param);
                        $list[$k]['follow_num'] = $m_info['follow_num'];
                        $list[$k]['fans_num']   = $m_info['follow_num'];
                        $list[$k]['info']       = $m_info['info'];
                    }
                }
            }
            $ret        = array(
                'code'  => 1,
                'total_results' => $count['sum'],
                'items' => $list,
                'msg'   => app::get('b2c')->_('读取成功'),
            );
        } else {
            $ret    = array (
                'code'  => -1,
                'msg'   => app::get('b2c')->_('请确保会员ID合法'),
            );
        }
        if ( $ret['code'] < 0 ) {
            $rpcService->send_user_error($ret['code'], $ret['msg']);
        }
        return $ret;
    }


    public function upload_image()
    {
		//return $_FILES['file']['name'].'llll';exit();
        # avatar 160 160
        # cover  640 316

        $uptype = $_POST['type'];


        if ($uptype != 'avatar' && $uptype != 'cover') $this->app->rpcService->send_user_error('4003', $uptype);

        $old_images = kernel::single('b2c_user_object')->get_members_data(array('members'=> $uptype));

        $size = array(
            'width'   => $uptype == 'avatar' ? '160' : '640',
            'height'  => $uptype == 'avatar' ? '160' : '316',
        );  // 尺寸

        $image = $this->imageUpload(3,$size);
		// return $image;
        // 更新图片
        app::get('b2c')->model('members')->update(array($uptype => $image['image_id']), array('member_id' => $this->app->member_id));

        // 删除旧图
        if ($old_images) {
            app::get('image')->model('image')->delete_image($old_images,'network');
        }
        $this->exp("upload_avatar",$this->app->member_id);
        return $image['image_url'];
    }

    private function fileext($filename)
    {
        return substr(strrchr($filename, '.'), 1);
    }



    private function get_start($nPage,$count)
    {
        $maxPage = ceil($count / $this->pagesize);
        if($nPage > $maxPage) $nPage = $maxPage;
        $start = ($nPage-1) * $this->pagesize;
        $start = $start<0 ? 0 : $start;
        $aPage['start'] = $start;
        $aPage['maxPage'] = $maxPage;
        return $aPage;
    }

    /**
     * 添加收藏商品
     */
    public function add_fav($param = array(), $rpcService)
    {
        $object_type = $param['type'];
        $nGid = $param['gid'];

        if(!$nGid) return false;
        $obj_member = app::get('b2c')->model('member_goods');

        if (!$obj_member->add_fav($this->app->member_id,$object_type,$nGid)){
            $rpcService->send_user_error('4003', '商品收藏添加失败！');
        }else{

            return '商品收藏添加成功';
        }
    }
	public function get_fav(){
		//return $this->app->member_id;
		$obj_member = app::get('b2c')->model('member_goods');
		if($obj_member->getList('*',array('member_id'=>$this->app->member_id,'goods_id'=>$_POST['gid']))){
			return true;
		}
		return false;
	}

    /**
     * 删除收藏商品
     */
    public function del_fav($param='', $rpcService)
    {
        $gid = $param['gid'];
        $object_type = $param['gid'] ? $param['gid'] : 'goods';
        if (!$gid) {
            $rpcService->send_user_error('4003', '参数错误！');
        }
        if (!kernel::single('b2c_member_fav')->del_fav($this->app->member_id,$object_type,$gid,$maxPage)){
            $rpcService->send_user_error('4003', '移除失败！');
        }else{
            return '成功移除！';
        }
    }

    /**
     * 我收藏商品列表
     */
    public function favorite($param = array())
    {
        $nPage = $param['n_page'] ? $param['n_page'] : 1;
        $page_size = $param['page_size'] ? $param['page_size'] : 10;
        $membersData = kernel::single('b2c_user_object')->get_members_data(array('members' => 'member_lv_id'));
        if (isset($param['mode']) && $param['mode'] == 'yts') {
            $members_id = isset($param['member_id']) ? $param['member_id'] : $this->app->member_id;
            $aData = @kernel::single('b2c_member_fav')->get_yts_fav($members_id, $membersData['members']['member_lv_id'], $nPage, $page_size);
            foreach ($aData as &$fav_item) {
                $fav_item['image_default_url'] = base_storager::image_path($fav_item['image_default_id'], 'm');
            }
            return $aData;
        } else {
            $aData = @kernel::single('b2c_member_fav')->get_favorite($this->app->member_id, $membersData['members']['member_lv_id'], $nPage, $page_size);
        }
        $aProduct = $aData['data'];
        foreach($aProduct as $k=>$v){
            $aProduct[$k]['image_default_url'] = base_storager::image_path($v['image_default_id'], 'm' );
            if($v['nostore_sell']){
                $aProduct[$k]['store'] = 999999;
                $aProduct[$k]['product_id'] = $v['spec_desc_info'][0]['product_id'];
            }else{
                foreach((array)$v['spec_desc_info'] as $value){
                    $aProduct[$k]['product_id'] = $value['product_id'];
                    $aProduct[$k]['spec_info'] = $value['spec_info'];
                    $aProduct[$k]['price'] = $value['price'];
                    if(is_null($value['store']) ){
                        $aProduct[$k]['store'] = 999999;
                        break;
                    }elseif( ($value['store']-$value['freez']) > 0 ){
                        $aProduct[$k]['store'] = $value['store']-$value['freez'];
                        break;
                    }else{
                        $aProduct[$k]['store'] = false;
                    }
                }
            }
        }

		if(isset($param['mode'])&&$param['mode']=='yts'){
			return $aProduct;
		}


        $aData = app::get('b2c')->model('goods_cat')->getList('cat_id, cat_name', array('parent_id' => 0, 'disabled'=>'false'));
        foreach ($aData as $key => $value) {
            foreach ($aProduct as $v) {
                if ($value['cat_id'] == $v['parent_cat_id']) {
                    $aData[$key]['product'][] = $v;
                }
            }
        }
        return $aData;
    }

    /**
     * 我的收入
     */
    public function promotion_into_logs(){

    	$sdf['page_no'] = $_POST['page_no'] ? $_POST['page_no'] : '1';
    	$sdf['page_size'] = $_POST['page_size'] ? $_POST['page_size'] : '20';

    	$page_no = intval($sdf['page_no']) - 1;
    	$page_size = intval($sdf['page_size']);

    	$where .= ' where 1 ';
    	$where .= " and pil.member_id = '".$this->app->member_id."' ";

    	$db = kernel::database();
    	$count_row = $db->selectrow("SELECT count(*) as row_count FROM `sdb_microshop_promotion_into_logs` as pil $where ");
    	$sum_row = $db->selectrow("SELECT SUM(pil.money) as total_money FROM `sdb_microshop_promotion_into_logs` as pil $where ");

    	$sql = "SELECT pil.money, pil.mtime, pi.order_id, pi.special_name, pi.name as product_name FROM `sdb_microshop_promotion_into_logs` as pil ".
      			" left join `sdb_microshop_promotion_into` as pi on pi.pri_id = pil.pri_id ".
    	      	" $where order by log_id desc LIMIT $page_no,$page_size;";

    	$pils = $db->select($sql);

    	if($pils){
	    	foreach ($pils as $key=>$v){
	    		$pils[$key]['format_mtime'] = date('m-d',$v['mtime']);
	    	}
    	}

    	return array('total_results'=>$count_row['row_count'],'total_money' => $sum_row['total_money']>0 ? $sum_row['total_money']:0, 'items'=>$pils);

    }

    /**
     * 未来评价的商品
     */
    public function nodiscuss($param = array(), $rpcService)
    {
        $nPage = $param['n_page'] ? $param['n_page'] : 1;
        $order_id = $param['order_id'] ? $param['order_id'] : false;
        //获取会员已发货的商品日志
        $sell_logs = app::get('b2c')->model('sell_logs')->getList('order_id,product_id,goods_id',array('member_id'=>$this->app->member_id));
        $_filter = array('author_id'=>$this->app->member_id,'object_type'=>'discuss','for_comment_id'=>'0');
        //获取会员已评论的商品
        $comments = app::get('b2c')->model('member_comments')->getList('order_id,product_id',$_filter);
        $data = array();
        if($comments){
            foreach((array)$comments as $row){
                if($row['order_id'] && $row['product_id']){
                    $data[$row['order_id']][$row['product_id']] = $row['product_id'];
                }
            }
        }

        foreach((array)$sell_logs as $key=>$log_row){
            if($data && $data[$log_row['order_id']][$log_row['product_id']] == $log_row['product_id']){
                unset($sell_logs[$key]);
            }else{
                if($order_id && $data[$log_row['order_id']][$log_row['order_id']] != $order_id){
                    $filter['order_id'][] = $order_id;
                }else{
                    $filter['order_id'][] = $log_row['order_id'];
                }
                $filter['product_id'][] = $log_row['product_id'];
                $filter['item_type|noequal'] = 'gift';
            }
        }

        $orderItemModel = app::get('b2c')->model('order_items');
        $limit = $this->pagesize;
        $start = ($nPage-1)*$limit;
        $i = 0;
        $nogift = $orderItemModel->getList('order_id,product_id',$filter);
        if($nogift){
            foreach($nogift as $row){
                $tmp_nogift_order_id[] = $row['order_id'];
                $tmp_nogift_product_id[] = $row['product_id'];
            }
        }
        foreach((array)$sell_logs as $key=>$log_row){
            if(in_array($log_row['order_id'],$tmp_nogift_order_id) && in_array($log_row['product_id'],$tmp_nogift_product_id) ){//剔除赠品,赠品不需要评论
                if($i >= $start && $i < ($nPage*$limit) ){
                    $sell_logs_data[] = $log_row;
                    $gids[] = $log_row['goods_id'];
                }
                if($nogift){
                    $i += 1;
                }
            }
        }
        $totalPage = ceil($i/$limit);
        if($nPage > $totalPage) $nPage = $totalPage;

        $result['pagination']['nPage'] = $nPage;
        $result['pagination']['totalPage'] = $totalPage;

        if($gids){
            //获取商品信息
            $goodsData = app::get('b2c')->model('goods')->getList('goods_id,name,image_default_id',array('goods_id'=>$gids));
            $goodsList = array();
            foreach((array)$goodsData as $goods_row){
                foreach ($sell_logs_data as $k => $v) {
                    if ($v['goods_id'] == $goods_row['goods_id']) {
                        $goodsList[$k]['goods_id'] = $goods_row['goods_id'];
                        $goodsList[$k]['product_id'] = $v['product_id'];
                        $goodsList[$k]['order_id'] = $v['order_id'];
                        $goodsList[$k]['goods_name'] = $goods_row['name'];
                        $goodsList[$k]['default_img_url'] = base_storager::image_path($goods_row['image_default_id'], 's' );
                    }
                }
            }
            shuffle($goodsList);
            $result['list'] = $goodsList;

            $result['point_status'] = app::get('b2c')->getConf('goods.point.status') ? app::get('b2c')->getConf('goods.point.status'): 'on';
            $result['verifyCode'] = app::get('b2c')->getConf('comment.verifyCode');
            if($result['point_status'] == 'on'){
                //评分类型
                $comment_goods_type = app::get('b2c')->model('comment_goods_type');
                $result['comment_goods_type'] = $comment_goods_type->getList('*');
                if(!$result['comment_goods_type']){
                    $sdf['type_id'] = 1;
                    $sdf['name'] = app::get('b2c')->_('商品评分');
                    $addon['is_total_point'] = 'on';
                    $sdf['addon'] = serialize($addon);
                    $comment_goods_type->insert($sdf);
                    $result['comment_goods_type'] = $comment_goods_type->getList('*');
                }
            }

        return $result;
        //$result['submit_comment_notice'] = $this->app->getConf('comment.submit_comment_notice.discuss');
        }
    }

    /**
     * 会员等级
     */
    public function levels_info($value='')
    {
        $data['uname'] = $this->member['uname'];
        #获取会员等级
        $obj_mem_lv = app::get('b2c')->model('member_lv');
        $levels = $obj_mem_lv->getList('name,disabled',array('member_lv_id'=>$this->member['member_lv']));
        if($levels[0]['disabled']=='false'){
            $data['levelname'] = $levels[0]['name'];
        }

        #还差多少点升级
        $switch_lv = $obj_mem_lv->get_member_lv_switch($this->member['member_lv']);
        if ($switch_lv['switch_type'] == 0 && $switch_lv['show'] == 'YES') {
            $data['next_lv'] = '还差'.($switch_lv['lv_data'] - $this->member['experience']).'成长值升级为'.$switch_lv['lv_name'];
        }

        #获取所有的会员等级信息
        $levels_list = $obj_mem_lv->getListAll();
        foreach ($levels_list as $key => $value) {
            $data['levels_list'][$key]['name'] = $value['name'];
            $data['levels_list'][$key]['dis_count'] = $value['dis_count'];
            $data['levels_list'][$key]['point'] = $value['point'];
            $range = $levels_list[$key+1]['point'] ? $levels_list[$key+1]['point']-1 : '无上限';
            $data['levels_list'][$key]['range'] = $value['point'].'-'.$range;
        }

        return $data;
    }

    /**
     * 绑定修改手机、邮箱
     * 验证会员密码
     */
    public function verify($param='')
    {
        unset($_SESSION['vcodeVerifykey']['activation']);
        $pamMembersModel = app::get('pam')->model('members');
        $pamData = $pamMembersModel->getList('login_password,password_account,createtime',array('member_id'=>$this->app->member_id));
        $use_pass_data['login_name'] = $pamData[0]['password_account'];
        $use_pass_data['createtime'] = $pamData[0]['createtime'];
        $login_password = pam_encrypt::get_encrypted_password(trim($param['password']),'member',$use_pass_data);
        if($login_password !== $pamData[0]['login_password']){
            $this->app->rpcService->send_user_error('password_error', '登录密码错误');
        }else{
            $_SESSION['vcodeVerifykey']['activation'] = 'true';
            return;
        }
    }

    /**
     * 绑定修改手机、邮箱
     * 提交保存信息
     */
    public function verify_vcode($param=''){
        if (!$_SESSION['vcodeVerifykey']['activation']) {
            $this->app->rpcService->send_user_error('password_error', '为保障您的账户安全，请先验证您的身份');
        }
        $send_type = 'reset';
        $userVcode = kernel::single('b2c_user_vcode');
        if( !$userVcode->verify($param['vcode'],$param['uname'],$send_type)){
            $msg = app::get('b2c')->_('验证码错误');
            $this->app->rpcService->send_user_error('fail', $msg);
        }

        $userPassport = kernel::single('b2c_user_passport');
        $accountType = $userPassport->get_login_account_type($param['uname']);
        if($send_type == 'reset'){
            if( !$userPassport->set_new_account($this->app->member_id,trim($param['uname']),$msg) ){
                $msg = $msg ? $msg : app::get('b2c')->_('修改信息失败');
                $this->app->rpcService->send_user_error('fail', $msg);
            }
        }
        //增加会员同步 2012-05-15
        if( $member_rpc_object = kernel::service("b2c_member_rpc_sync") ) {
            $member_rpc_object->modifyActive($this->app->member_id);
        }

        return '修改成功';
    }
	/* * *--------------------2014.11.二次开发.549224868@qq.com--------------------start---------* * */

	 /**
     * 我提现申请列表
     */
    public function withdrawal($param = array(), $rpcService){

        $param['page_no'] = $param['page_no'] ? max(1,(int)$param['page_no']) : '1';
        $param['page_size'] = $param['page_size'] ? (int)$param['page_size'] : '10';

        $page_size = $param['page_size'];
        $page_no = ($param['page_no'] - 1) * $page_size;

        $db = kernel::database();
        $member = app::get('b2c')->model('members');
        $mem_wit = kernel::single('b2c_mdl_member_withdrawal');

        $sql = "SELECT * FROM `sdb_b2c_member_withdrawal` WHERE member_id='".$this->app->member_id."'";
        $witlogs = $db->select(" $sql order by  id desc LIMIT $page_no, $page_size");
        $rs = $db->select("SELECT count(*) FROM `sdb_b2c_member_withdrawal` WHERE member_id='".$this->app->member_id."'");
        if(!$rs[0]['count']){
        	$total_results = $rs[0]['count'];
        }

        $data['total_results'] = $total_results?$total_results:0;
        $total = $member->dump($this->app->member_id,'advance');
        $where = " where member_id = '".$this->app->member_id."' and has_op=3 ";
        $sum_row = $db->selectrow("SELECT SUM(amount) as total_withdrawal FROM `sdb_b2c_member_withdrawal` $where ");

        $data['total'] = $total['advance']['total'];
        $data['total_withdrawal'] = $sum_row['total_withdrawal']?$sum_row['total_withdrawal']:0;

        $data['witlogs'] = $witlogs;
        return $data;
    }

    /**
     * 申请提现
     */
    public function submit_withdrawal($param = array(), $rpcService){
		$msg = 'false';
		if($param['money'] >= 100){
			if(!kernel::single('b2c_mdl_member_bank')->getList('*',array('member_bank_id'=>$param['member_bank_id']))){
				$rpcService->send_user_error('4003', '您提现的卡号不存在');
			}
			$members = kernel::single('b2c_mdl_members');
			$mem_v = $members->getList('advance,advance_freeze',array('member_id'=>$this->app->member_id));
			if($mem_v[0]['advance']  > $param['money']){
				$data = array(
					'member_id'=>$this->app->member_id,
					'amount'=>$param['money'],
					'member_bank_id'=>$param['member_bank_id'],
					'create_time'=>time(),
					'remark'=>$param['remark']
				);
				//return $data;
				$res = kernel::single('b2c_mdl_member_withdrawal')->insert($data);

				if($res){
					$advance_now = $mem_v[0]['advance'] - $param['money'];
                                        $current_shop_advance = kernel::single('b2c_mdl_member_advance')->get_shop_advance();
                                        $shop_advance = $current_shop_advance-$_POST['money'];
                                        if($shop_advance<0){
                                            $msg = '提现操作失败，请重试';
                                        }

					$mem_data = $mem_v[0]['advance_freeze']+$param['money'];
					$sql = "UPDATE sdb_b2c_members SET `advance`='{$advance_now}',`advance_freeze`='{$mem_data}' WHERE `member_id` = ".$this->app->member_id;
					$res1 = kernel::database()->exec($sql);
					if($res1){
						//$members->getList('advance,advance_freeze',array('member_id'=>$this->app->member_id));
						return '提现申请成功，请耐心等待客服人员联系!';
					}else{
						$msg = '提现申请失败!';
					}
				}else{
					$msg = '提现操作失败，请重试';
				}
			}else{
				$msg = '您的预存款余额不足';
			}
		}else{
			$msg = '提现金额最少100元';
		}
        $rpcService->send_user_error('4003', $msg);
    }

	//微店等级获取
	public function get_member_shop_lv() {
        $lv_id = kernel::single('microshop_mdl_shop')->getList('shop_lvl', array('member_id' => $this->app->member_id));
        $res = kernel::single('microshop_mdl_shop_lv')->getList('lv_name', array('shop_lv_id' => $lv_id[0]['shop_lvl']));
        if ($res) {
            return $res[0]['lv_name'];
        }
        $this->app->rpcService->send_user_error('4003', '查询失败');
    }

	//获取会员等级
	public function get_member_dengji(){
		$lv_id = kernel::single('b2c_mdl_members')->getList('member_lv_id', array('member_id' => $this->app->member_id));
        $res = kernel::single('b2c_mdl_member_lv')->getList('name', array('member_lv_id' => $lv_id[0]['member_lv_id']));
        if ($res) {
            return $res[0]['name'];
        }
        $this->app->rpcService->send_user_error('4003', '查询失败');
	}

    /**
     * 	获取银行卡信息
     */
    public function get_banklists() {
        $Bank = kernel::single('b2c_mdl_member_bank');
        $banklists = $Bank->getList('*', array('member_id' => $this->app->member_id),$this->offset,$this->page_nums);
        return $banklists;
    }

	//获取银行卡数量
	public function get_banknums(){
		$res = 	kernel::single('b2c_mdl_member_bank')->count(array('member_id'=>$this->app->member_id));
		return empty($res)?0:$res;
	}

    //添加新的银行卡
    public function addbankcard() {

        $userVcode = kernel::single('b2c_user_vcode');
        if( !$vcodeData = $userVcode->verify($_POST['vcode'],$_POST['mobile'],'activation')){
            $msg = app::get('b2c')->_('验证码错误');
            $this->app->rpcService->send_user_error('verify_error', $msg);
        }

        if (!empty($this->data_post['bank_num'])) {
            $this->data_post['member_id'] = $this->app->member_id;
            $this->data_post['create_time'] = time();
            $res = kernel::single('b2c_mdl_member_bank')->save($this->data_post);
            if ($res) {
                return true;
            }
        }
        $this->app->rpcService->send_user_error('4003', '添加失败');
    }

    //删除已绑定的银行卡
    public function delete_bankcard() {
        //$_POST = $this->check_input($_POST);
        if (!empty($_POST['member_bank_id'])) {
            if (kernel::single('b2c_mdl_member_bank')->delete(array('member_bank_id' => $this->data_post['member_bank_id']))) {
                return true;
            }
        }
        $this->app->rpcService->send_user_error('4003', '操作失败');
    }

     public function get_bonus_detail(){
        $this->where.=' AND `member_id`='.$this->app->member_id;
        $this->where.=" AND `memo`='佣金/提成'";
        $this->where .= ' AND `import_money` > 0';
        $this->where .= ' ORDER by mtime DESC';
        $sql='SELECT * FROM sdb_b2c_member_advance '.$this->where.' LIMIT '.$this->offset.','.$this->page_nums;
        $count = kernel::database()->select("SELECT count(*) as total FROM sdb_b2c_member_advance {$this->where}");
        //return $count;
		$rows = kernel::database()->select($sql);
        foreach ($rows as $k=>$v){
            $tmp=  explode(':', trim($v['message']));
            if(mb_substr($tmp[0],0,2,'utf-8')=='直接'){
                $member_id=  intval($tmp[1]);
                $members=app::get('b2c')->model('members')->dump($member_id);
                $login_name=app::get('pam')->model('members')->get_operactor_name($member_id);
                if($members['name']){
                    $rows[$k]['message']='微店分销：'.$members['name'];
                }else{
                    $rows[$k]['message']='微店分销：'.$login_name;
                }
            }else{
                $rows[$k]['message']='微店分销：间接分销';
            }
        }
		$this->app->rpcService->send_user_success('200',$rows,$count[0]['total']);
        //return $rows;
    }

    //客户订单
      public function get_corder(){
        $this->where.=' AND a.member_id='.$this->app->member_id;
        if($_POST['fx_id']){
            $this->where.=' AND p.member_id='.$_POST['fx_id'];
            }
        // $this->where.=" AND a.memo='佣金/提成'";
        $this->where .= ' AND a.import_money > 0';
        $this->where .= " AND p.status = 'finish'";
        $this->where .= ' ORDER by a.mtime DESC';
        $sql='SELECT * FROM sdb_b2c_member_advance AS a INNER JOIN `sdb_b2c_orders` AS p ON a.order_id=p.order_id '.$this->where.' LIMIT '.$this->offset.','.$this->page_nums;
        $count = kernel::database()->select("SELECT count(*) as total FROM sdb_b2c_member_advance AS a left JOIN `sdb_b2c_orders` AS p ON a.order_id=p.order_id {$this->where}");
        $summoney = kernel::database()->select("SELECT sum(import_money) as total  FROM sdb_b2c_member_advance AS a left JOIN `sdb_b2c_orders` AS p ON a.order_id=p.order_id {$this->where}");



        $rows = kernel::database()->select($sql);

        foreach ($rows as $k=>$v){

            $rows[$k]['status'] = $this-> get_order_status($v['order_id']);
            $rows[$k]['summoney']=$summoney[0]['total'];
             $tmp=  explode(':', trim($v['message']));

                $member_id=  intval($tmp[1]);
               $members=app::get('b2c')->model('members')->dump($member_id);
               $login_name=app::get('pam')->model('members')->get_operactor_name($member_id);
                $rows[$k]['login_name'] = $login_name;
                $rows[$k]['name'] = $this-> get_name($member_id);



            //     $rows[$k]['summoney']=$summoney[0]['total'];



        }
        $this->app->rpcService->send_user_success('200',$rows,$count[0]['total']);
        //return $rows;
    }

  //获取未完成订单
     //客户订单
      public function get_ncorder(){



      $this->where.=' AND a.member_id='.$this->app->member_id;
        if($_POST['fx_id']){
            $this->where.=' AND p.member_id='.$_POST['fx_id'];
            }
        // $this->where.=" AND a.memo='佣金/提成'";
        $this->where .= ' AND a.import_money > 0';
        $this->where .= " AND p.status = 'active'";
        $this->where .= " AND p.pay_status = '1'";
        $this->where .= ' ORDER by a.mtime DESC';
        $sql='SELECT * FROM sdb_b2c_member_advance AS a INNER JOIN `sdb_b2c_orders` AS p ON a.order_id=p.order_id '.$this->where.' LIMIT '.$this->offset.','.$this->page_nums;
        $count = kernel::database()->select("SELECT count(*) as total FROM sdb_b2c_member_advance AS a left JOIN `sdb_b2c_orders` AS p ON a.order_id=p.order_id {$this->where}");
        $summoney = kernel::database()->select("SELECT sum(import_money) as total  FROM sdb_b2c_member_advance AS a left JOIN `sdb_b2c_orders` AS p ON a.order_id=p.order_id {$this->where}");



        $rows = kernel::database()->select($sql);

        foreach ($rows as $k=>$v){

            $rows[$k]['status'] = $this-> get_order_status($v['order_id']);
            $rows[$k]['summoney']=$summoney[0]['total'];
             $tmp=  explode(':', trim($v['message']));

                $member_id=  intval($tmp[1]);
               $members=app::get('b2c')->model('members')->dump($member_id);
               $login_name=app::get('pam')->model('members')->get_operactor_name($member_id);
                $rows[$k]['login_name'] = $login_name;
                $rows[$k]['name'] = $this-> get_name($member_id);


            //     $rows[$k]['summoney']=$summoney[0]['total'];



        }


       kernel::single('b2c_mdl_member_advance')->update(array('status'=>'1'),array('member_id'=>$this->app->member_id,'status'=>'0'));


        $this->app->rpcService->send_user_success('200',$rows,$count[0]['total']);
        //return $rows;
    }

//获取支付订单未完成状态
    public function get_order_status($order_id){
       $res = kernel::single('b2c_mdl_orders')->getList('status',array('order_id'=>$order_id,'pay_status'=>1));
       if($res){
            return $res[0]['status'];
        }
        return '0';
    }


    /**
     * 获取账户余额
     */
    public function get_member_wallet(){
        $PayDetail = kernel::single('b2c_mdl_members');
        $res = $PayDetail->getList('advance',array('member_id'=>$this->app->member_id));
        if($res){
            return $res[0]['advance'];
        }
        $this->app->rpcService->send_user_error('4003','查询失败');
    }

    /**
     * 账户充值
     */
    public function member_recharge(){
        $PayDetail = kernel::single('b2c_mdl_member_advance');
        $data = $this->check_input($_POST);
        if($data['pay_num'] > 0 && $data['pay_status']){
           $member_advance = $this->get_member_wallet();
           $data['mtime']  = time();

           if($data['import_money'] > 0){
               $data['member_advance'] =  $data['import_money'] + $member_advance;
               $data['message'] = '存入';
           }else{
               $data['member_advance'] =  $member_advance - $data['explode_money'];
               $data['message'] = '支出';
           }
           $data['member_id'] = $this->app->member_id;
           if($PayDetail->insert($data)){
                return true;
            }
        }
        $this->app->rpcService->send_user_error('4003','充值失败');
    }

    /*
     * 	收支明细
     */
    public function get_payment_detail() {
		//return $this->data_post;

		if(!empty($this->data_post['pay_status'])){
			if($this->data_post['pay_status'] == '+'){
				$this->where .= ' AND p.import_money > 0';
			}else{
				$this->where .= ' AND a.explode_money > 0';
			}
		}
        $this->where.=' AND a.member_id='.$this->app->member_id;
        $this->where .= " AND p.status = 'finish'";
        $this->where .= " AND p.pay_status = '1'";
        $this->where .= ' ORDER by a.mtime DESC';

		//return $this->where;
        $res =  kernel::database()->select('SELECT * FROM sdb_b2c_member_advance AS a INNER JOIN `sdb_b2c_orders` AS p ON a.order_id=p.order_id '.$this->where.' LIMIT '.$this->offset.','.$this->page_nums);
        //$count = kernel::database()->select("select count(log_id) as total from sdb_b2c_member_advance where member_id = {$this->app->member_id}");
		$count = kernel::single('b2c_mdl_member_advance')->count(array('member_id'=>$this->app->member_id));

		$this->app->rpcService->send_user_success('200',$res,$count);
    }

    /**
     * 用户提现申请
     */
    public function member_mention_now(){


        return TRUE;
    }

    /**
     * 获取用户相关信息
     */
    public function get_member_aloneinfo(){
        $res = kernel::single('b2c_mdl_members')->getList('mobile,name,firstname,lastname',array('member_id'=>$this->app->member_id));
		if($res){
			//$avatar = kernel::single('b2c_mdl_image_image')->getList('s_url',array('image_id'=>$res[0]['avatar']));
			//$res[0]['pic'] = $avatar[0]['s_url'];
			$res[0]['show_name'] = $this->get_member_showname($this->app->member_id);
			return $res;
		}
		return false;
    }

    /**
     *  获取我的经销商
     */
    public function get_member_distributor(){
		$DB = kernel::database();
        $res = kernel::single('microshop_mdl_shop_jingxiao')->getList('*', array('member_id' => $this->app->member_id),$this->offset,$this->page_nums,$this->data_post['orderby']);
        foreach ($res as $k => $v) {
            $res[$k]['show_name'] = $this->get_member_showname($v['jx_mem_id'], $DB);
        }
        return $res;
    }

	protected function get_jingxiao_id() {
        return kernel::single('microshop_mdl_shop_jingxiao')->getList('*', array('member_id' => $this->app->member_id));
    }

    protected function get_fenxiao_id() {
        return kernel::single('microshop_mdl_shop_fenxiao')->getList('*', array('member_id' => $this->app->member_id));
    }


   public function get_my_info(){
      $DB = kernel::database();
       $res = kernel::single('b2c_mdl_members')->getList('*', array('member_id' => $this->app->member_id),$this->offset,$this->page_nums,$this->data_post['orderby']);



        if(is_array($res)){

            foreach ($res as $k => $v) {
                $res[$k]['show_name'] = $this->get_member_showname($v['member_id'], $DB);
                $res[$k]['huanxin_id'] = $this-> get_huanxin($v['member_id']);
                $res[$k]['name'] = $this-> get_name($v['member_id']);
                $res[$k]['login_name'] = $this->get_login_name($v['member_id']);
                $res[$k]['avatar'] = $this->get_avatar($v['member_id']);
                $res[$k]['wx_name'] = $this->get_wx_name($v['member_id']);
                $res[$k]['mobile'] = $this->get_mobile($v['member_id']);
                $res[$k]['shangxian'] = $this->get_mobile($v['member_id']);
                $res[$k]['sxname'] = $this-> get_name($v['invite_mem_fid']);
                $res[$k]['lv'] = $this->get_sx($v['member_id']);
                $res[$k]['gongxian'] = $this->get_my_gongxian($v['member_id']);



            }
            //return $res;
            $this->app->rpcService->send_user_success('200',$res,1);
        }
        $this->app->rpcService->send_user_error('4003','暂无分销商列表');
   }
    public function get_noread(){
        $member_id = $this->app->member_id;

        if($count = kernel::database()->select("SELECT count(*) as total FROM sdb_b2c_member_advance where member_id = {$member_id} and status = '0'")){
            return $count;
        }
        return '';
    }

    public function read(){
        if($_POST['order_id']&&$_POST['read']){

            if(kernel::single('b2c_mdl_member_advance')->update(array('status'=>'1'),array('member_id'=>$this->app->member_id,'order_id'=>$_POST['order_id']))){
                return '已读';
            }
        }
        else return '0';
    }


    public function get_my_gongxian($member_id){
        if($res = kernel::single('microshop_mdl_shop_fenxiao')->getList('gongxian', array('fx_mem_id' => $member_id))){
            return $res[0]['gongxian'];
        }
        return '0';
    }



   /**
     *  获取我的分销商
     */
    public function get_member_bedistributor(){
        $DB = kernel::database();
        if($_POST['member_id']){
            $member_id=$_POST['member_id'];
        }else{
            $member_id= $this->app->member_id;
        }



        $res = kernel::single('microshop_mdl_shop_fenxiao')->getList('*', array('member_id' => $member_id));



        if(is_array($res)){
            $count = kernel::database()->select("SELECT count(*) as total FROM sdb_microshop_shop_fenxiao where member_id = {$member_id}");
            foreach ($res as $k => $v) {
                $res[$k]['show_name'] = $this->get_member_showname($v['fx_mem_id'], $DB);
                $res[$k]['huanxin_id'] = $this-> get_huanxin($v['fx_mem_id']);
                $res[$k]['name'] = $this-> get_name($v['fx_mem_id']);
                $res[$k]['login_name'] = $this->get_login_name($v['fx_mem_id']);
                $res[$k]['avatar'] = $this->get_avatar($v['fx_mem_id']);
                $res[$k]['wx_name'] = $this->get_wx_name($v['fx_mem_id']);
                $res[$k]['mobile'] = $this->get_mobile($v['fx_mem_id']);
                $res[$k]['shangxian'] = $this->get_mobile($v['fx_mem_id']);
                $res[$k]['sxname'] = $this-> get_name($v['member_id']);
                $res[$k]['lv'] = $this->get_sx($v['fx_mem_id']);
                $res[$k]['member_id'] = $member_id;




            }
            //return $res;
            $error=array();
            if($_POST['member_id']){
                if($this->check_sx($member_id)==1){
                     $this->app->rpcService->send_user_success('200',$res,$count[0]['total']);

                }else{
                     $this->app->rpcService->send_user_success('200',$error,1);
                }
            }


             $this->app->rpcService->send_user_success('200',$res,$count[0]['total']);

        }
        $this->app->rpcService->send_user_error('4003','暂无分销商列表');
    }





    public function get_mem_id($fx_mem_id){
        if($res = kernel::single('microshop_mdl_shop_fenxiao')->getList('member_id', array('fx_mem_id' => $fx_mem_id))){
           return $res[0]['member_id'];
        }
        return '0';
    }
    public function check_sx($member_id){
         $row = kernel::single('b2c_mdl_members')->getList('member_agency_id', array('member_id' => $this->app->member_id));

        if($row[0]['member_agency_id'] != 0&&$row[0]['member_agency_id'] !='0'){
            return 1 ;
        }


        $j = 3;
        for ($i=0; $i < $j-1; $i++) {
          $member_id = $this->get_mem_id($member_id);

         if($member_id ==$this->app->member_id){
            return 1;
          }
        }
         return 0;




    }


    //获取上线
    public function get_sx($member_id){
        $row = kernel::single('b2c_mdl_members')->getList('invite_mem_fid,member_lv_id,member_agency_id', array('member_id' => $member_id));

        $edu = kernel::single('b2c_mdl_member_lv')->getList('name',array('member_lv_id'=>$row[0]['member_lv_id']));

        $edv = kernel::single('b2c_mdl_member_agency')->getList('name',array('member_agency_id'=>$row[0]['member_agency_id']));
        if($row[0]['member_agency_id']>0){
            return $edv[0]['name'];
        }else{
            return $edu[0]['name'];
        }
    }


    //获取电话
     public function get_mobile($member_id){
         if($res= kernel::single('pam_mdl_members')->getList('login_account',array('member_id'=>$member_id))){

             return $res[0]['login_account'];
         }
         return '';
    }

    //获取头像
    public function get_avatar($member_id){
         if($res= kernel::single('b2c_mdl_members')->getList('avatar',array('member_id'=>$member_id))){
             $res[0]['avatar'] = $res[0]['avatar'] ? base_storager::image_path($res[0]['avatar'],'l') : kernel::get_resource_host_url()."/headPlaceHolder_big@2x.png";
             if ($res[0]['avatar']=='') {
                 return  kernel::get_resource_host_url()."/headPlaceHolder_big@2x.png";
             }
             return $res[0]['avatar'];
         }
         return  kernel::get_resource_host_url()."/headPlaceHolder_big@2x.png";
    }
    //获取微信号
    public function get_wx_name($member_id){
         if($res= kernel::single('microshop_mdl_shop')->getList('wx_name',array('member_id'=>$member_id))){

             return $res[0]['wx_name'];
         }
         return '微信号';
    }

    //获取登录名
     public function get_login_name($member_id){
         if($res= kernel::single('pam_mdl_members')->getList('login_account',array('member_id'=>$member_id))){
             return $res[0]['login_account'];
         }
         return '';
    }




    //获取昵称
    public function get_name($member_id){
         if($res= kernel::single('b2c_mdl_members')->getList('name',array('member_id'=>$member_id))){
             return $res[0]['name'];
         }
         return '匿名';
    }

    /*
    *   member_id
    *   环信登录帐号密码获取
    */
    public function get_huanxin($member_id){
        if($res = kernel::single('b2c_mdl_member_to_huanxin')->getList('username',array('member_id'=>$member_id))){
            return $res[0]['username'];
        }
        return '';
    }

	//我的客户
    public function get_member_customer(){
		$DB = kernel::database();
        $res = kernel::single('microshop_mdl_shop_custom')->getList('*', array('member_id' => $this->app->member_id),$this->offset,$this->page_nums,$this->data_post['orderby']);
        if(is_array($res)){
            $count = kernel::database()->select("SELECT count(*) as total FROM sdb_microshop_shop_custom where member_id = {$this->app->member_id}");
            foreach ($res as $k => $v) {
                $res[$k]['show_name'] = $this->get_member_showname($v['cs_mem_id'], $DB);
            }
            //return $res;
            $this->app->rpcService->send_user_success('200',$res,$count[0]['total']);
        }
		$this->app->rpcService->send_user_error('4003','暂无客户列表');
    }

    /**
     *  获取我的采购
     */
    public function get_member_purchase(){
		$Orders = kernel::single('b2c_mdl_order');
		$res = $Orders->getList('order_id,cost_item,ship_status,pay_status',array('member_id'=>$this->app->member_id),$this->offset,$this->page_nums);
		if($res){
			return $res;
		}
		return false;
    }

    /**
     *  获取我的库存
     */
    public function get_member_stock(){
        $Mygoods = kernel::single('microshop_mdl_shop_goods');
        $Products = kernel::single('b2c_mdl_products');
		$ArchiveOrder = kernel::single('b2c_mdl_archive_order_items');
		$res = $Mygoods->getList('*',array('member_id'=>$this->app->member_id),$this->offset,$this->page_nums);
		$fields = 'product_id,title,name,price';
		if(is_array($res)){
			foreach($res as $k=>$v){
				$product = $Products->getList("{$fields}",array('product_id'=>$v['product_id']));
				$res[$k]['product'] = $product[0];
				$sale_num = $ArchiveOrder->count(array('product_id'=>$v['product_id'],'from_mem_id'=>$this->app->member_id));
				$res[$k]['sale_num'] = $sale_num;
			}
			return $res;
		}
		return false;

    }
	//我下线的用户ID集合
	protected function get_my_xiaxian() {
        $jingxiao = $this->get_jingxiao_id();
        $fenxiao = $this->get_fenxiao_id();
        $xx_ids = '';
        if (is_array($jingxiao)) {
            foreach ($jingxiao as $v_jx) {
                $xx_ids .= $v_jx['jx_mem_id'];
            }
        }
        if (is_array($fenxiao)) {
            foreach ($fenxiao as $v_fx) {
                $xx_ids .= $v_fx['fx_mem_id'];
            }
        }
        $xx_ids = rtrim($xx_ids, ',');
        return $xx_ids;
    }

    /**
     *  获取我的销售。平台销售
     */
    public function get_member_sale(){
		return $this->get_customer_data('=');
    }
	//我的销售数据,三方自营销售
	protected function get_customer_data($type = '>'){

        $DB = kernel::database();
		$this->where .= ' AND sdb_b2c_goods.third_merchant_id '.$type.' 0 AND sdb_b2c_goods.goods_id = sdb_b2c_order_items.goods_id';
		if(!empty($this->data_post['orderby'])){
			$this->where .= ' ORDER BY '.$this->data_post['orderby'];
		}

        $res = $DB->select('SELECT buy_mem_id,gongxian,order_id FROM sdb_b2c_order_items,sdb_b2c_goods '.$this->where.' LIMIT '.$this->offset.','.$this->page_nums);
		if(is_array($res)){
			$Orders = kernel::single('b2c_mdl_orders');
			foreach ($res as $k => $v) {
				$time = $Orders->getList('createtime', array('order_id' => $v['order_id']));
				$res[$k]['time'] = $time[0]['createtime'];
				$res[$k]['show_name'] = $this->get_member_showname($v['buy_mem_id'], $DB);
			}
			return $res;
		}
        return false;

	}

	//获取我的销售。下线销售
    public function get_member_linesale() {
        return $this->get_customer_data('>');
    }

	//获取会员当前显示名
    public function get_member_showname($member_id,$DB = kernel::database) {
		if ($member_id > 0) {
			$data = array(
				'member_id'=>$member_id,
				'is_checked'=>3
			);
			if($rel_name = kernel::single('b2c_mdl_member_auth')->getList('name',$data)){
				return $rel_name[0]['name'];
			}
            $name = $DB->select("select name,lastname,firstname sdb_b2c_members where member_id = '{$member_id}'");
            if (!empty($name[0]['name'])) {
                return $name[0]['name'];
            } else {
              //  $name = $DB->select("select login_account from sdb_pam_members where members_id = '{$member_id}'");
                $name=  app::get('pam')->model('members')->get_operactor_name($member_id);
                return $name;
            }
        }
        return false;
    }

	//客服热线
    public function get_kefu_tellphone() {

        return '400-6868-6767';
    }

    //意见反馈
    public function save_member_yijian() {

    }

	//好友列表显示	9，已经被邀请过了	8，未被邀请		1-7,在被邀请的1-7天当中		10,暂停邀请
    public function get_friends_list() {
		if (is_array($this->data_post)) {
			$this->data_post['sign'] = null;
			$this->data_post['date'] = null;
			unset($this->data_post['sign']);
			unset($this->data_post['date']);
            $res = array();
            $DB = kernel::database();
            $Members = kernel::single('b2c_mdl_members');
			$a = 0;
			//return $this->data_post;
            foreach ($this->data_post as $k_f=>$v_friend) {
				$arr[$a] = $this->get_friend_num($v_friend,$k_f,$DB,$Members);
				$a++;
            }
            return $arr;
        }
		return false;
    }

	protected function get_friend_num($v_friend,$k_f,$DB,$Members){
		$mobile = str_replace('+86','',$v_friend);
		$mobile = str_replace(' ','',$mobile);

		$arr['id'] = $k_f;
		$arr['mobile'] = $v_friend;
		$parent = $Members->getList('parent_id,member_id,name', array('mobile' =>$mobile));
		$res = $DB->select("select member_id from sdb_pam_members where login_account = '{$mobile}'");
		//return $res;exit();
		if ($parent[0]['parent_id'] > 0 || $parent[0]['member_id'] > 0 || $res[0]['member_id'] > 0) {
			$arr['status'] = 9;
		} else {
			$time = time() - 7 * 24 * 3600;
			$where = " invite_phone = '{$mobile}' and invite_time > '{$time}'";
			$res = $DB->select("SELECT member_id,invite_time FROM sdb_b2c_member_invite WHERE {$where} LIMIT 1");
			//return $where;
			if ($res) {
				$arr['status'] = ceil((time() - $res[0]['invite_time'])/24/3600);
			} else {
				$time = time() - 14 * 24 * 3600;
				if($DB->select("SELECT member_id FROM sdb_b2c_member_invite WHERE invite_phone = '{$mobile}' AND member_id != '{$this->app->member_id}' invite_time > '{$time}' ")){
					$arr['status'] = 10;
				}else{
					$arr['status'] = 8;
				}
			}
		}
		return $arr;
	}

	//实名认真
	public function check_real_membername(){
		$res = $this->get_check_rel_membername();
		if($res[0]['is_checked'] == 3){
			return $res;
		}
		if(strlen($this->data_post['identity_num']) == 18){
			if(!empty($this->data_post['real_name'])){

				$image = $this->imageUpload();

				$this->data_post['uptime'] = time();
				$this->data_post['member_id'] = $this->app->member_id;
				$this->data_post['upimage'] = $image['image_url'];
				$this->data_post['image_id'] = $image['image_id'];
				if(app::get('b2c')->model('member_auth')->insert($this->data_post)){
					return true;
				}
			}else{
				return '真实名字不能为空';
			}
		}else{
			return '身份证号码不正确';
		}
		return false;
	}

	//获取的认真信息
	public function get_check_rel_membername(){
		return kernel::single('b2c_mdl_member_auth')->getList('*',array('member_id'=>$this->app->member_id),0,1,'uptime DESC');
	}

	//更改手机绑定
	public function change_member_mobile(){
		if(strlen($this->data_post['mobile']) && strlen($this->data_post['mobile']) == 11){
			if(kernel::single('b2c_mdl_members')->update(array('mobile'=>$this->data_post['mobile']),array('member_id'=>$this->app->member_id))){
				return '修改成功';
			}
		}
		return false;
	}

	//更改用户昵称
	public function change_member_name(){
		if(!empty($this->data_post['name']) && mb_strlen($this->data_post['name']) < 15){
			if(kernel::single('b2c_mdl_members')->update($this->data_post,array('member_id'=>$this->app->member_id))){
				return '修改成功';
			}
		}else{
			return '您的昵为空或太长';
		}
		return false;
	}

	//用户邀请验证
	public function check_member_invitephone(){


		return true;
	}

	//获取购物宝数量
	public function get_buygoods_nums(){
		$res = kernel::single('microshop_mdl_shop')->getList('buymoney',array('member_id'=>$this->app->member_id));
		return $res[0]['buymoney'];
	}

	//购物宝的消费记录
	public function get_buygoods_sales(){
		$this->where .= ' AND `member_id` = '.$this->app->member_id;
		if(!empty($this->data_post['pay_type'])){
			if($this->data_post['pay_type'] == '+'){
				$this->where .= ' AND `import_money` > 0';
			}else{
				$this->where .= ' AND `explode_money` > 0';
			}
		}
        return kernel::database()->select('SELECT * FROM sdb_b2c_member_buymoney '.$this->where.' LIMIT '.$this->offset.','.$this->page_nums);
	}


	//获取微店的基本信息
	public function get_shop_info(){

		$res = kernel::single('microshop_mdl_shop')->getList('*',array('member_id'=>$this->app->member_id));
		if($res){
			if(empty($res[0]['wx_name'])){
				$res[0]['wx_name'] = '您还没有设置微信号呢';
			}
			if(empty($res[0]['desc'])){
				$res[0]['desc'] = '您还没有给您的微店写点简介呢';
			}
			return $res;
		}
		return false;
	}

	//修改微信信息
	public function edit_shop_info(){
		if($this->data_post['shop_id'] > 0){
			if(kernel::single('microshop_mdl_shop')->save($this->data_post)){
				return '修改成功';
			}
		}
		return false;
	}

	//自营商品上传，添加
	public function add_goods_fromthird(){
		if($this->data_post['goods_id'] > 0){
			$image = $this->imageUpload();
			$data = array(
					'target_id'=>$this->data_post['goods_id'],
					'target_type'=>'goods',
					'image_id'=>$image['image_id']
					);
			if(kernel::single('image_mdl_image_attach')->insert($data)){
				return true;
			}
			$this->app->rpcService->send_user_error('4003', '上传失败，请重新上传');
		}
		if($this->data_post['store'] <= 0){
			$this->app->rpcService->send_user_error('4003', '库存错误');
		}
		if(!empty($this->data_post['name']) && !empty($this->data_post['price']) && !empty($this->data_post['intro'])){

			$image = $this->imageUpload();
			//return $image;
			$this->data_post['image_default_id'] = $image['image_id'];
			$this->data_post['marketable'] = 'true';
			$this->data_post['uptime'] = time();
			$this->data_post['last_modify'] = time();
			$this->data_post['third_merchant_id'] = $this->app->member_id;

			$goods_id = kernel::single('b2c_mdl_goods')->insert($this->data_post);
			//return $goods_id.'uyuyu';
			if($goods_id > 0){
				$data = array(
							'goods_id'=>$goods_id,
							'store'=>$this->data_post['store'],
							'price'=>$this->data_post['price'],
							'name'=>$this->data_post['name'],
							'title'=>$this->data_post['title']
							);
				$product_id = kernel::single('b2c_mdl_products')->insert($data);
				return $goods_id;
			}

			$this->app->rpcService->send_user_error('4003', '添加失败，请重试');
		}
		$this->app->rpcService->send_user_error('4003', '选项不能为空');
	}

	//图片上传公共类
	protected function imageUpload($max_size=3,$size=''){
		if(empty($size)){
			$size == array('width'=> '400','height'=> '300');
		}
		if ($_FILES['file']['size'] > ($max_size * 1024 * 1024)) {
			$this->app->rpcService->send_user_error('4003', '上传文件不能超过3M！');
		}

		if ( $_FILES['file']['name'] != "" ) {
			$type = array("png","jpg","gif","jpeg"); //允许上传的文件

			if(!in_array(strtolower($this->fileext($_FILES['file']['name'])), $type)) {
				$text = implode(",", $type);
				$this->app->rpcService->send_user_error('4003', '您只能上传以下类型文件'.$text);
			}
		}

		$mdl_img = app::get('image')->model('image');

		$image_name = $_FILES['file']['name'];
		//return $_FILES;
		$image_id = $mdl_img->store($_FILES['file']['tmp_name'],null,null,$image_name);

		//return $image_id;
		$mdl_img->rebuild($image_id,array('l','m','s'));
		$image_src = base_storager::image_path($image_id, 'l');
		//return 'baid.com';
		if(empty($image_id)){
			$this->app->rpcService->send_user_error('4013', '文件上传失败，请重新上传');
			exit();
		}
		return array(
					'res'=>'success',
					'image_id'=>$image_id,
					'image_url'=>$image_src,
					'image_name'=>$image_name
					);
	}
    //身份证列表
    function idcards(){
        $cardmdl = app::get('b2c')->model('addr_card');
        $res = $cardmdl->getList('*',array('member_id'=>$this->app->member_id));
        foreach ($res as $k => $v) {
           $arr[$k] = $v;
           $arr[$k]['forward_url'] = base_storager::image_path($v['forward'], 's');
           $arr[$k]['back_url'] = base_storager::image_path($v['back'], 's');

        }

        return $arr;
    }

    //保存身份证信息
    function save_idcard(){
           $cardmdl = app::get('b2c')->model('addr_card');

           $arr['member_id'] =$this->app->member_id;
           $arr['create_time'] = time();
          if ($_POST['addr_id']) {
             $addrmdl = app::get('b2c')->model('member_addrs');
             $res = $addrmdl->getList('name,card_num',array('addr_id'=>$_POST['addr_id']));
             if ($_POST['id']) {
                $img = $cardmdl->getList('forward,back',array('id'=>$_POST['id']));
                $image1['image_id']=$img[0]['forward'];
                $image2['image_id']=$img[0]['back'];
                $arr['id'] = $_POST['id'];
             }else{
              $image1 = $this->imageUpload1();
              $image2 = $this->imageUpload2();
             }
             $arr['forward'] = $image1['image_id'];
             $arr['back'] = $image2['image_id'];
             $arr['real_name'] = $res[0]['name'];
             $arr['card_num'] = $res[0]['card_num'];
             $arr['addr_id'] = $_POST['addr_id'];

          }else{
              return false;
          }
            if ($cardmdl->save($arr)) {
                   $arr['forward'] = base_storager::image_path($arr['forward'], 's');
                   $arr['back'] = base_storager::image_path($arr['back'], 's');
           }else{
               return false;
           }
         return $arr;
    }
    //删除身份证
    function del_idcard(){
       $cardmdl = app::get('b2c')->model('addr_card');
           if (!empty($_POST['id'])) {
            if ($cardmdl->delete(array('id' => $_POST['id']))) {
                 return 'succ';
            }
        }
        $this->app->rpcService->send_user_error('4003', '操作失败');
    }

    //图片上传公共类
    protected function imageUpload1($max_size=3,$size=''){
        if(empty($size)){
            $size == array('width'=> '400','height'=> '300');
        }
        if ($_FILES['file0']['size'] > ($max_size * 1024 * 1024)) {
            $this->app->rpcService->send_user_error('4003', '上传文件不能超过3M！');
        }

        if ( $_FILES['file0']['name'] != "" ) {
            $type = array("png","jpg","gif","jpeg"); //允许上传的文件

            if(!in_array(strtolower($this->fileext($_FILES['file0']['name'])), $type)) {
                $text = implode(",", $type);
                $this->app->rpcService->send_user_error('4003', '您只能上传以下类型文件'.$text);
            }
        }

        $mdl_img = app::get('image')->model('image');

        $image_name = $_FILES['file0']['name'];
        //return $_FILES;
        $image_id = $mdl_img->store($_FILES['file0']['tmp_name'],null,null,$image_name);

        //return $image_id;
        $mdl_img->rebuild($image_id,array('l','m','s'));
        $image_src = base_storager::image_path($image_id, 'l');
        //return 'baid.com';
        if(empty($image_id)){
            $this->app->rpcService->send_user_error('4013', '文件上传失败，请重新上传');
            exit();
        }
        return array(
                    'res'=>'success',
                    'image_id'=>$image_id,
                    'image_url'=>$image_src,
                    'image_name'=>$image_name
                    );
    }
     protected function imageUpload2($max_size=3,$size=''){
        if(empty($size)){
            $size == array('width'=> '400','height'=> '300');
        }
        if ($_FILES['file1']['size'] > ($max_size * 1024 * 1024)) {
            $this->app->rpcService->send_user_error('4003', '上传文件不能超过3M！');
        }

        if ( $_FILES['file1']['name'] != "" ) {
            $type = array("png","jpg","gif","jpeg"); //允许上传的文件

            if(!in_array(strtolower($this->fileext($_FILES['file1']['name'])), $type)) {
                $text = implode(",", $type);
                $this->app->rpcService->send_user_error('4003', '您只能上传以下类型文件'.$text);
            }
        }

        $mdl_img = app::get('image')->model('image');

        $image_name = $_FILES['file1']['name'];
        //return $_FILES;
        $image_id = $mdl_img->store($_FILES['file1']['tmp_name'],null,null,$image_name);

        //return $image_id;
        $mdl_img->rebuild($image_id,array('l','m','s'));
        $image_src = base_storager::image_path($image_id, 'l');
        //return 'baid.com';
        if(empty($image_id)){
            $this->app->rpcService->send_user_error('4013', '文件上传失败，请重新上传');
            exit();
        }
        return array(
                    'res'=>'success',
                    'image_id'=>$image_id,
                    'image_url'=>$image_src,
                    'image_name'=>$image_name
                    );
    }

	//推荐好友验证信息
	public function tuijian_friend_log(){
		if(!empty($this->data_post['invite_phone']) && $this->data_post['member_id'] == $this->app->member_id){
				$arr = $this->get_friend_num($this->data_post['invite_phone'],1,kernel::database(),kernel::single('b2c_mdl_members'));

				if($arr['status'] == 8){
					$mobile = str_replace('+86','',$this->data_post['invite_phone']);
					$mobile = str_replace(' ','',$mobile);
					$data['invite_phone'] = $mobile;
					$data['member_id'] = $this->app->member_id;
					$data['invite_time'] = time();

					if(kernel::single('b2c_mdl_member_invite')->insert($data)){
						return true;
					}
				}
		}
		return false;
	}

	//增加退款
	public function   tuikuan()
	{


		$order_id=$this->data_post['order_id'];

		$member_id=$this->app->member_id;


		if(!is_numeric($order_id))
		{
			return "订单编号只能为数字";
			exit();
		}


		$orders_tui = kernel::database()->select("SELECT *  FROM sdb_b2c_member_tui where order_id = {$order_id} ");

		if($orders_tui)
		{
			return "此订单已经在退款中";
			exit();
		}

		$orders = kernel::database()->select("SELECT total_amount,member_id  FROM sdb_b2c_orders where order_id = {$order_id} and member_id={$member_id} ");



		if(!$orders)
		{
			return "此订单号不存在";
			exit();
		}



		$sdf['member_id'] = $orders[0]["member_id"];

        $sdf['cur_money'] = $orders[0]["total_amount"];


		$sdf['order_id'] = $order_id;

		$sdf['edit_time'] = time();

		$member_tui = app::get('b2c')->model('member_tui');

		$member_tui->insert($sdf);

		return "申请退款成功";

	}

    //by 设置支付密码
    function setpaypassword($params){
        $verifyType = $params['type'] ? $params['type'] : 'setpaypassword';
        if($verifyType == 'setpaypassword' || $verifyType == 'verifypaypassword'){
            $pay_password = $_POST['pay_password'];
            $re_pay_password = $pay_password;
            if($pay_password !== $re_pay_password){
                $msg = app::get('b2c')->_('您输入的密码不一致');
                kernel::single('base_rpc_service')->send_user_error('setpaypassword',$msg);
            }
            if(mb_strlen($pay_password)<6 || mb_strlen($re_pay_password)<6){
                $msg = app::get('b2c')->_('请输入正确格式的密码');
                kernel::single('base_rpc_service')->send_user_error('setpaypassword',$msg);
            }
            $password = pam_encrypt::get_encrypted_password(trim($pay_password),pam_account::get_account_type(app::get('b2c')->app_id),$use_pass_data);
            if(app::get('b2c')->model('members')->update(array('pay_password'=>$password),array('member_id'=>$this->app->member_id))){
                app::get('b2c')->model('members_error')->update(array('error_num'=>'0'),array('member_id'=>$this->app->member_id,'type' => 'check'));
            }
            return true;
        }
        else{
            $send_type = $_POST['send_type'];
            $userVcode = kernel::single('b2c_user_vcode');
            if( !$userVcode->verify($_POST['vcode'],$_POST['uname'],$send_type)){
                $msg = app::get('b2c')->_('验证码错误');
                kernel::single('base_rpc_service')->send_user_error('setpaypassword',$msg);
            }

            $userPassport = kernel::single('b2c_user_passport');
            $accountType = $userPassport->get_login_account_type($_POST['uname']);
            if($_POST['send_type'] == 'reset'){
                if( !$userPassport->set_new_account($this->app->member_id,trim($_POST['uname']),$msg) ){
                    $msg = $msg ? $msg : app::get('b2c')->_('修改信息失败');
                    kernel::single('base_rpc_service')->send_user_error('setpaypassword',$msg);
                }
            }else{
                if( !app::get('pam')->model('members')->update(array('login_account'=>$_POST['uname'],'disabled'=>'false'),array('member_id'=>$this->app->member_id,'login_type'=>$accountType)) ){
                    $msg = app::get('b2c')->_('重置信息失败');
                    kernel::single('base_rpc_service')->send_user_error('setpaypassword',$msg);
                }
            }
            //增加会员同步 2012-05-15
            if( $member_rpc_object = kernel::service("b2c_member_rpc_sync") ) {
                $member_rpc_object->modifyActive($this->app->member_id);
            }
            return true;
        }
    }


    public function coupon_code($coupon=''){
        if (empty($coupon['coupon'])) {
            $this->app->rpcService->send_user_error('4003', '优惠券码不能为空');
        }

        $membersData = kernel::single('b2c_user_object')->get_current_member();
        $memberId = intval($membersData['member_id']); //会员id号
        $mdl_member_coupon = app::get('b2c')->model('member_coupon');
        $prefix = kernel::single('mobileapi_rpc_starbuy_special')->cutstr($coupon['coupon'], 2);
        $prefix = strtoupper($prefix);
        if (in_array($prefix, array('VA', 'VB', 'VC'))) {
            $coupon['coupon'] = preg_replace('/^VA|VB|VC/i', "A", $coupon['coupon'], 1);
            if ($mdl_member_coupon->getList('*', array('memc_code' => $coupon['coupon'], 'member_id' => $memberId))) {
                $this->app->rpcService->send_user_error('4003', '您已拥有该优惠券，无需兑换');
            }
        } else {
            if ($mdl_member_coupon->getList('*', array('memc_code' => $coupon['coupon'], 'member_id' => $memberId))) {
                $this->app->rpcService->send_user_error('4003', '此优惠码已经兑换过，不能重复兑换');
            }
        }

        $mdl_coupons = app::get('b2c')->model("coupons");
        if (!$mdl_coupons->verify_coupons($coupon, $msg)) {
            $msg = $msg ? $msg : app::get('b2c')->_('优惠券添加失败！');
            $this->app->rpcService->send_user_error('4003', $msg);
        }



        $coupon_info = $mdl_coupons->getCouponByCouponCode($coupon['coupon']);
            $couponData = array('memc_code' => $coupon['coupon'], 'cpns_id' => $coupon_info[0]['cpns_id'], 'member_id' => $memberId, 'memc_gen_time' => time());
            if ($mdl_member_coupon->insert($couponData)) {

                $input = array('isfastbuy'=>false,'coupon'=>$coupon['coupon'],'is_return'=>1);
                $re = kernel::single('mobileapi_rpc_cart')->add_coupon($input);
                $re_coupon = $this->coupon('1', '', $coupon['coupon']);
                if($re['success']){
                    $re_coupon[0]['can_use'] = 1;

                }else{
                    $re_coupon[0]['can_use'] = 0;
                }
                $re_coupon[0]['rule_info']['name'] = str_replace("优惠劵规则-", "", $re_coupon[0]['rule_info']['name']);
                sort($re_coupon);
                return $re_coupon;
            } else {
                $this->app->rpcService->send_user_error('4003', '系统错误');
            }

        /*
          //这是凭优惠码领取其他优惠券程序
          if($starbuy_special=kernel::single('mobileapi_rpc_starbuy_special')->add_coupon($coupon_info[0]['cpns_id'])){
          return '兑换成功';
          };
         */
    }
    public function attention($filter){
        $member_fans_model = app::get('b2c')->model('member_fans');
        $count = $member_fans_model->count($filter);
        $data=array();
        if($count>0){
            return false;
        }
        if($filter['member_id'] == $filter['fans_id']){
            return false;
        }
        $input = array(
            'member_id' => $filter['member_id'],
            'fans_id' => $filter['fans_id'],
            'created' => time(),
        );
        if(!$re = $member_fans_model->insert($input)){
            return false;
        }else{
            $member_count = $member_fans_model->count(array('member_id'=>$filter['member_id']));
            $fans_count = $member_fans_model->count(array('fans_id'=>$filter['fans_id']));
            app::get('b2c')->model('members')->update(array('fans_num'=>$member_count),array('member_id'=>$filter['member_id']));
            app::get('b2c')->model('members')->update(array('follow_num'=>$fans_count),array('member_id'=>$filter['fans_id']));
            $input = array(
                'member_id' => $filter['member_id'],
                'message_type' => 'fans',
                'is_read' => '0',
                'time' => time()
            );
            app::get('b2c')->model('member_message')->insert($input);
            return true;
        }

    }
    public function un_attention($filter){
        $member_fans_model = app::get('b2c')->model('member_fans');
        if(!$re = $member_fans_model->delete($filter)){
            return false;
        }else{
            $member_count = $member_fans_model->count(array('member_id'=>$filter['member_id']));
            $fans_count = $member_fans_model->count(array('fans_id'=>$filter['fans_id']));
            app::get('b2c')->model('members')->update(array('fans_num'=>$member_count),array('member_id'=>$filter['member_id']));
            app::get('b2c')->model('members')->update(array('follow_num'=>$fans_count),array('member_id'=>$filter['fans_id']));
            return $re;
        }

    }
    public function get_fans($filter){
        if(!$filter['member_id']){
            return false;
        }
//        if($filter['member_id'] == $this->app->member_id){
//            app::get('b2c')->model('member_message')->update(array('is_read'=>1),array('member_id'=>$this->app->member_id,'message_type'=>'fans'));
//
//        }
        $page = $filter['page'] ? $filter['page'] : 1;
        $limit = $filter['limit'] ? $filter['limit'] : 5;
        $member_fans_model = app::get('b2c')->model('member_fans');
        $re = $member_fans_model->getList("*",array('member_id'=>$filter['member_id']),($page-1)*$limit,$limit,"id desc");
        foreach($re as $k=>$fans){
            $re[$k]['created'] = date("Y-m-d H:i:s",$fans['created']);
            $member = app::get("b2c")->model("members")->getRow("*",array('member_id'=>$fans['fans_id']));
            $is_attention = $member_fans_model->count(array('fans_id'=>$this->app->member_id,'member_id'=>$fans['fans_id']));
            $re[$k]['is_attention'] = $is_attention ? 1 : 0;
            $re[$k]['name'] = $member['name'] ? $member['name'] : "[未设置]";
            $re[$k]['avatar'] = $member['avatar'] ? base_storager::image_path($member['avatar'],'l') : kernel::get_resource_host_url()."/headPlaceHolder_big@2x.png";
            $re[$k]['member_lv_id'] = $member['member_lv_id']-1;
            $re[$k]['fans_num'] = $member['fans_num'];
            $re[$k]['opinions_num'] = $member['opinions_num'];
            $re[$k]['praise_num'] = $member['praise_num'];
        }
        return $re;
    }
    public function get_attention($filter){
        if(!$filter['member_id']){
            return false;
        }
        $page = $filter['page'] ? $filter['page'] : 1;
        $limit = $filter['limit'] ? $filter['limit'] : 5;
        $member_fans_model = app::get('b2c')->model('member_fans');
        $re = $member_fans_model->getList("*",array('fans_id'=>$filter['member_id']),($page-1)*$limit,$limit,"id desc");
        foreach($re as $k=>$fans){
            $re[$k]['created'] = date("Y-m-d H:i:s",$fans['created']);
            $member = app::get("b2c")->model("members")->getRow("*",array('member_id'=>$fans['member_id']));
            $is_attention = $member_fans_model->count(array('fans_id'=>$this->app->member_id,'member_id'=>$fans['member_id']));
            $re[$k]['is_attention'] = $is_attention ? 1 : 0;
            $re[$k]['name'] = $member['name'] ? $member['name'] : "[未设置]";
            $re[$k]['avatar'] =$member['avatar'] ? base_storager::image_path($member['avatar'],'l') : kernel::get_resource_host_url()."/headPlaceHolder_big@2x.png";
            $re[$k]['member_lv_id'] = $member['member_lv_id']-1;
            $re[$k]['fans_num'] = $member['fans_num'];
            $re[$k]['opinions_num'] = $member['opinions_num'];
            $re[$k]['praise_num'] = $member['praise_num'];
        }
        return $re;

    }
    //判断手机号是否注册
    function mobile_list($filter){
        if(!$filter['mobiles']){
            return FALSE;
        }
        $mobiles = json_decode($filter['mobiles'],true);
        //return $mobiles;
        $re = array('reg'=>array(),'no_reg'=>array());
        foreach($mobiles as $val){
            $mb = trim(str_replace("-","",str_replace("+86", "", $val['mobile'])));
            $flag = app::get('pam')->model('members')->getRow("*",array('login_type'=>'mobile','login_account'=>$mb));
            if($flag){
                $member = app::get('b2c')->model('members')->getRow("*",array('member_id'=>$flag['member_id']));
                $is_attention = app::get('b2c')->model('member_fans')->count(array('fans_id'=>$this->app->member_id,'member_id'=>$member['member_id']));
                $re['reg'][] = array(
                    'mobile' => $mb,
                    'nickname' => $member['name'] ? $member['name'] : '[未设置]',
                    'avatar' =>$member['avatar'] ? base_storager::image_path($member['avatar'],'l') : kernel::get_resource_host_url()."/headPlaceHolder_big@2x.png",
                    'is_attention' => $is_attention ? 1 : 0,
                    'name' => $val['name'],
                    'member_id' => $flag['member_id']

                );
            }else{
                $re['no_reg'][] = array(
                    'mobile' => $val['mobile'],
                    'name' =>$val['name']
                );
            }
        }
        return $re;
    }
    //判断微博好友是否注册
    function weibo_list($filter){
        if(!$filter['weibos']){
            return FALSE;
        }
        $weibos = json_decode($filter['weibos'],true);
        //return $mobiles;
        $re = array('reg'=>array(),'no_reg'=>array());
        foreach($weibos as $val){
            $flag = app::get('pam')->model('members')->getRow("*",array('login_type'=>'local','login_account|head'=>"sina_",'login_account|foot'=>"_".$val['uid']));
            if($flag){
                $member = app::get('b2c')->model('members')->getRow("*",array('member_id'=>$flag['member_id']));
                $is_attention = app::get('b2c')->model('member_fans')->count(array('fans_id'=>$this->app->member_id,'member_id'=>$member['member_id']));
                $re['reg'][] = array(
                    'uid' => $val['uid'],
                    'nickname' => $member['name'] ? $member['name'] : '[未设置]',
                    'avatar' => $member['avatar'] ? base_storager::image_path($member['avatar'],'l') : kernel::get_resource_host_url()."/headPlaceHolder_big@2x.png",
                    'is_attention' => $is_attention ? 1 : 0,
                    'name' => $val['name'],
                    'member_id' => $flag['member_id'],
                    'opinions_num' => $member['opinions_num'],
                    'fans_num' => $member['fans_num'],

                );
            }else{
                $re['no_reg'][] = array(
                    'uid' => $val['uid'],
                    'name' =>$val['name']
                );
            }
        }
        return $re;
    }
    //获取未推荐的订单

    public function get_order_opinions(){
        //return $this->app->member_id;
		//return $_POST;
        $nPage = $_POST['n_page'] ? $_POST['n_page'] : 1;
	$status = 'finish';  //订单状态

        $order = app::get('b2c')->model('orders');

        $order_status = array();
                    //return $pay_status;

        //订单状态
        if (isset($status) && $status == 'finish') {
            $order_status['status'] = 'finish';
        }


                    //return $order_status;
        $aData = $order->fetchByMember($this->app->member_id,$nPage,$order_status);

        $this->get_order_details($aData,'member_orders');
        $oImage = app::get('image')->model('image');
        $oGoods = app::get('b2c')->model('goods');
        $imageDefault = app::get('image')->getConf('image.set');
        $obj_payments_cfgs = app::get('ectools')->model('payment_cfgs');
        foreach($aData['data'] as $k => &$v) {
            foreach($v['goods_items'] as $k2 => &$v2) {
                $spec_desc_goods = $oGoods->getList('spec_desc',array('goods_id'=>$v2['product']['goods_id']));
                $select_spec_private_value_id = @reset($v2['product']['products']['spec_desc']['spec_private_value_id']);
                $spec_desc_goods = @reset($spec_desc_goods[0]['spec_desc']);
                if($spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']){
                    list($default_product_image) = explode(',', $spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']);
                    $v2['product']['thumbnail_pic'] = $default_product_image;
                }else{
                    if( !$v2['product']['thumbnail_pic'] && !$oImage->getList("image_id",array('image_id'=>$v['image_default_id']))){
                        $v2['product']['thumbnail_pic'] = $imageDefault['S']['default_image'];
                    }
                    $v2['product']['thumbnail_pic_src'] = base_storager::image_path($v2['product']['thumbnail_pic'], 's' );
                }
            }
            $v['goods_num'] = count($v['goods_items']);
            if ($v['payinfo']['pay_app_id']) {
               $aData['data'][$k]['payinfo']['display_name'] = $obj_payments_cfgs->get_app_display_name($v['payinfo']['pay_app_id']);
            }
        }

        foreach ($aData['data'] as $key => $value) {
            unset($aData['data'][$key]['goods_items']);
            $aData['data'][$key]['goods_items'] = array_values($value['goods_items']);
            if ($value['consignee']['area']) {
                $str = explode(':', $value['consignee']['area']);
                $aData['data'][$key]['consignee']['txt_area'] = str_replace('/','',$str[1]);
            }
        }
        $deliveryMdl=  app::get('b2c')->model('delivery');

       foreach ($aData['data'] as $key => $value) {
           $delivery=$deliveryMdl->getList('logi_name,logi_no',array('order_id'=>$value['order_id']));
           $dly= kernel::single('b2c_mdl_dlycorp') ->getList('corp_code',array('name'=>$delivery[0]['logi_name']));
           $aData['data'][$key]['logi_name']=$delivery[0]['logi_name'];
           $aData['data'][$key]['logi_no']=$delivery[0]['logi_no'];
           $aData['data'][$key]['corp_code']=$dly[0]['corp_code'];
       }
       foreach($aData['data'] as $key => $value){
           $is_opinions = 1;
            foreach($value['goods_items'] as $k=>$val){
                $goods = app::get('b2c')->model('goods')->getRow("*",array('goods_id'=>$val['product']['goods_id']));
                if(!$goods){
                    $aData['data'][$key]['goods_items'][$k]['product']['is_opinions'] = 1;
                    $val['product']['is_opinions'] = 1;
                    $aData['data'][$key]['goods_items'][$k]['product']['is_comment'] = 1;
                    $val['product']['is_comment'] = 1;
                }
                $brand = app::get('b2c')->model('brand')->get_brand_name_for_goods_id($val['product']['goods_id']);
                $aData['data'][$key]['goods_items'][$k]['product']['brand_name'] = $brand;
                if(!$val['product']['is_opinions'] && !$val['product']['is_comment']){
                    $is_opinions = 0;
                }
            }
            if($is_opinions == 1){
                unset($aData['data'][$key]);
            }
        }
        usort($aData['data'], function($a, $b) {
            $al = $a['createtime'];
            $bl = $b['createtime'];
            return ($al > $bl) ? -1 : 1;
        });

        return $aData['data'];

    }

    public function queit($change=''){
		$member_id=$this->app->member_id;
		$mdl_members=app::get('b2c')->model('members');
		if(empty($change['change'])){
			$membersData=$mdl_members->getRow('queit',array('member_id'=>$member_id));
			return $membersData;
		}else{
			if($change['change']=='true'){
				if($mdl_members->update(array('queit'=>'true'),array('member_id'=>$member_id))){
					return array('queit'=>'true');
				}
			}else if($change['change']=='false'){
				if($mdl_members->update(array('queit'=>'false'),array('member_id'=>$member_id))){
					return array('queit'=>'false');
				}
			}
		}
		$this->app->rpcService->send_user_error('4003','系统错误');
    }

    //获取推荐商品
    function get_opinions(){
        $res = app::get('b2c')->model('orders')->getList('order_id',array('pay_status'=>1,'ship_status'=>1,'member_id'=>$this->app->member_id));
        foreach ($res as $k => $v) {
           $a[$k]=$this->get_opitems($v['order_id']);
        }
        return $a;
    }
    //获取达人推荐
    function get_members_for_doyen(){

        $page = $_REQUEST['page'] ? $_REQUEST['page'] : 1;
        $limit = $_REQUEST['limit'] ? $_REQUEST['limit'] : 20;
        $re = app::get('b2c')->model('members')->getList('member_id,name,avatar,member_lv_id,fans_num,opinions_num,praise_num',array('member_id|noequal'=>$this->app->member_id),($page-1)*$limit,$limit,"opinions_num+0.5*fans_num+0.3*praise_num desc");

        foreach($re as $k=>$fans){
            $is_attention = app::get("b2c")->model("member_fans")->count(array('fans_id'=>$this->app->member_id,'member_id'=>$fans['member_id']));
            $re[$k]['is_attention'] = $is_attention ? 1 : 0;
            $re[$k]['name'] = $fans['name'] ? $fans['name'] : "[未设置]";
            $re[$k]['avatar'] = $fans['avatar'] ? base_storager::image_path($fans['avatar'],'l') : kernel::get_resource_host_url()."/headPlaceHolder_big@2x.png";
        }
        return $re;
    }
    //搜索用户
    function search_member($filter){
        foreach($filter as $k=>$v){
                $filter[$k] = strip_tags($v);
        }
        $key = $filter['key'];

        $page = $filter['page'] ? $filter['page'] : 1;
        $limit = $filter['limit'] ? $filter['limit'] : 20;
        if($key){
            $sql = "select m.member_id,m.name,m.avatar,m.member_lv_id,m.fans_num,m.opinions_num,m.praise_num from ".kernel::database()->prefix."pam_members p left join ".kernel::database()->prefix."b2c_members m ON m.member_id = p.member_id "
                . " where p.login_account like '%".$key."%' and p.disabled = 'false' and p.member_id != ".$this->app->member_id." order by m.opinions_num+0.5*m.fans_num+0.3*m.praise_num desc";
        }else{
            return false;
        }
        $re = kernel::database()->selectLimit($sql,$limit,($page-1)*$limit);
        foreach($re as $k=>$fans){
            $is_attention = app::get("b2c")->model("member_fans")->count(array('fans_id'=>$this->app->member_id,'member_id'=>$fans['fans_id']));
            $re[$k]['is_attention'] = $is_attention ? 1 : 0;
            $re[$k]['name'] = $fans['name'] ? $fans['name'] : "[未设置]";
            $re[$k]['avatar'] = $member['avatar'] ? base_storager::image_path($member['avatar'],'l') : kernel::get_resource_host_url()."/headPlaceHolder_big@2x.png";
        }
        return $re;
    }

    function get_opitems($order_id){
      $res = app::get('b2c')->model('order_items')->getList('*',array('order_id'=>$order_id));
      foreach ($res as $key => $v) {
          $b[$key]['goods'] = $v;
          $b[$key]['goodsData'] = $this->get_goods($v['goods_id']);
          $resArr[$key]=array_merge($b[$key]['goods'],$b[$key]['goodsData']);
          //$resArr[$key]['opinions']=$this->get_opinions($v['goods_id'],$v['order_id']);
      }
      return $resArr;
    }

    function get_goods($goods_id){
        $goodsModel = app::get('b2c')->model('goods');
        $goodsData = $goodsModel->getList('name,price,store,image_default_id,brand_id',array('goods_id'=>$goods_id));
        foreach($goodsData as $k=>$v){
            $goodsData[$k]['img'] = kernel::single('base_storager')->image_path($v['image_default_id']);
            $goodsData[$k]['brand'] = $this->get_brand($v['brand_id']);
        }
        return $goodsData[0];

    }
    function get_brand($brand_id){
        $brandModel = app::get('b2c')->model('brand');
        $brandData = $brandModel->getList('brand_name',array('brand_id'=>$brand_id));
        return $brandData[0]['brand_name'];

    }
    // function get_opinions($goods_id,$order_id){
    //     $db = kernel::database();
    //     $sql = 'select * FROM `sdb_b2c_goods_opinions` AS p LEFT JOIN `sdb_b2c_goods_opinions_image` AS g ON p.id = g.opinions_id  WHERE p.order_id = '.$order_id.' and p.goods_id = '.$goods_id;
    //     $counts = $db->selectrow($sql);
    //     return $counts;
    // }


}
